存储setInterval的值

Jam*_*air 2 javascript setinterval

如果我有这样的代码

count=0
count2=setInterval('count++',1000)
Run Code Online (Sandbox Code Playgroud)

count2变量总是设置为2而不是count的实际值,因为它每秒都会增加

我的问题是:你甚至可以存储seInterval()方法的值

Ple*_*and 5

setInterval()的返回值是一个ID号,可以传递给clearInterval()以阻止定期执行的函数再次运行.这是一个例子:

var id = setInterval(function() {
    // Periodically check to see if the element is there
    if(document.getElementById('foo')) {
        clearInterval(id);
        weAreReady();
    }
}, 100);
Run Code Online (Sandbox Code Playgroud)

在您的示例中,如果您想要count2与count具有相同的值,则可以使用:

var count = 0, count2 = 0;
setInterval(function() {
    // I wrote this on two lines for clarity.
    ++count;
    count2 = count;
}, 1000);
Run Code Online (Sandbox Code Playgroud)