如何清除分配给同一变量的两个setIntervals?

时间:2017-03-21 17:57:29

标签: javascript ecmascript-6 prototype ecmascript-5

据我所知,我们可以将clearInterval as:



var go = setInterval(function() {
  console.log("go");
}, 5000);

clearInterval(go);




但由于某种原因,在我的javascript代码中,我有两次相同的变量分配setInterval。现在,即使我多次清除它也不会被清除。示例:



var go = setInterval(function(){
  console.log("go");
}, 1000);

var go = setInterval(function(){
  console.log("go");
}, 1000);

clearInterval(go);
clearInterval(go);

clearInterval(go);
clearInterval(go);




我的问题是:

这里发生了什么? javascript如何处理这种情况? go有什么问题?为什么它没有被清除?

2 个答案:

答案 0 :(得分:1)

你做不到。您已覆盖之前的计时器ID。它输了。

只有第二个时间间隔(当前存储在变量中的ID)将被清除,无论您拨打clearInterval的频率如何。

您将需要多个变量(或定时器的数据结构,例如数组):

var go1 = setInterval(function(){
  console.log("go 1");
}, 1000);

var go2 = setInterval(function(){
  console.log("go 2");
}, 1000);

clearInterval(go1);
clearInterval(go1); // nothing will happen
clearInterval(go2);

答案 1 :(得分:1)

正如一些评论中所述,您在此处所做的是重新分配您的go变量。每次调用setInterval都会返回不同的ID。一旦您重新分配了引用该值的唯一变量,之前的值就会丢失。

当涉及到唯一标识符时,它会保留一个可扩展的列表,以便您不会丢失该进程的标识符。我建议创建一个数组并将每个新id推送到它(使用它就像一个堆栈),这样它们都在一个地方,但仍然可以单独引用:

var intervalIDs = []; //we would want something like this to be a global variable
//adding IDs to the array:
intervalIDs.push(window.setInterval(function(){console.log("go 1");}, 1000));
intervalIDs.push(window.setInterval(function(){console.log("go 2");}, 1000));
//now we know we can find both IDs in the future
//clearing an interval:
window.clearInterval(intervalIDs.pop()); //takes the last ID out of the array and uses it to stop that interval. this could be done in a for loop to clear every one you've set using the above method.
//OR if you happen to know the index (in the array) of a specific interval id you want to clear:
var index = /*index number*/;
window.clearInterval(intervalIDs.splice(index, 1)[0]);

重点是确保您保持引用间隔的方式(或其他任何类似行为的方式)。

相关问题