Javascript 如何清除分配给同一变量的两个设置间隔?

Javascript 如何清除分配给同一变量的两个设置间隔?,javascript,ecmascript-6,prototype,ecmascript-5,Javascript,Ecmascript 6,Prototype,Ecmascript 5,据我所知,我们可以: var go=setIntervalfunction{ console.loggo; }, 5000; clearIntervalgo 你不能。您已覆盖上一个计时器id。它已丢失 无论调用clearInterval的频率如何,只有第二个间隔(其id当前存储在变量中)将被清除 您需要多个变量或计时器的数据结构,例如数组: var go1 = setInterval(function(){ console.log("go 1"); }, 1000); var go2 =

据我所知,我们可以:

var go=setIntervalfunction{ console.loggo; }, 5000;
clearIntervalgo 你不能。您已覆盖上一个计时器id。它已丢失

无论调用clearInterval的频率如何,只有第二个间隔(其id当前存储在变量中)将被清除

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

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);

正如一些评论中提到的,您在这里所做的是重新分配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]);

关键是要确保您保持引用间隔或其他类似行为的方法。

您不能这样做。您已覆盖上一个计时器id。它已丢失。如果您清除它,它将指向您的第一个计时器。相关:常量将阻止您重新分配Intervalidt这是一个很好的问题,为什么它有这么多的反对票?stackoverflow对初学者的问题有抵抗力吗?谢谢你的回答。javascript在哪里存储go的前一个实例?javascript引擎在堆栈中分配了两个空格吗?并没有以前的实例。只有一个空格,当变量写入前一个值时,将不再存储该值。