简体   繁体   English

如何用 javasript 停止 setInterval?

[英]How to stop setInterval with javasript?

I want to start from 0. Until it reaches the numbers 709 and 54, Stop it.我想从 0 开始。直到它到达数字 709 和 54,停止它。

HTML HTML

<span class="card-title h5 counter"> 709 + </span>
<span class="card-title h5 counter"> 54+ </span>

script.js脚本.js

let intervals = [];
let counter  = [];
let elements = document.getElementsByClassName('counter');
Array.from(elements).forEach((element, index) => {
    counter[index] = 0;
    intervals[index] = setInterval(()=> {
            counter[index]++;
            element.innerText=counter;
        }
        , 50);
})

But this code goes on indefinitely and does not end.但这段代码会无限期地继续下去,不会结束。

this way...这边走...

use the same setInterval for both, and clear it when there is no more counter to increment.对两者使用相同的setInterval ,并在没有更多计数器递增时将其清除。

 const elements = [...document.querySelectorAll('.counter')].map(el=>({el,counter:parseInt(el.textContent), val:-1})) let intervalReference = setInterval(() => { let endingCount = 0 elements.forEach(refs => { if ( refs.val < refs.counter) refs.el.textContent = ` ${++refs.val} + ` else ++endingCount }) if (endingCount===elements.length) clearInterval(intervalReference) }, 50)
 <span class="card-title h5 counter"> 709 + </span> <span class="card-title h5 counter"> 54+ </span>

You can use the below code snippet, the setInterval can be stopped with the help of clearInterval.您可以使用下面的代码片段,setInterval 可以在 clearInterval 的帮助下停止。

var intervalId = null;
var varCounter = 0;
var varName = function(){
     if(varCounter <= 709) {
          varCounter++;
          /* your code goes here */
     } else {
          clearInterval(intervalId);
     }
};

$(document).ready(function(){
     intervalId = setInterval(varName, 10000);
});

You can also do it in two separate setInterval() calls.您也可以在两个单独的setInterval()调用中执行此操作。 Each one is defined within their own scope.每一个都在自己的 scope 中定义。 This way there is no need to set up arrays for storing the values and references outside the scope:这样就不需要设置 arrays 来存储 scope 之外的值和引用:

 [...document.querySelectorAll('.counter')].forEach(e=>{ let i=0; const n=parseInt(e.textContent), h=setInterval(()=>{ if(i<n) e.textContent=++i +" + "; else clearInterval(h); },20) });
 <span class="card-title h5 counter"> 709 + </span> <span class="card-title h5 counter"> 54 + </span>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM