storing the value of setInterval

2019-05-24 07:15发布

if I had a code like this

count=0
count2=setInterval('count++',1000)

the count2 variable would always set as 2 not the actual value of count as it increases every second

my question is: can you even store the value of the seInterval() method

3条回答
迷人小祖宗
2楼-- · 2019-05-24 07:29

The return value of setInterval() is an ID number that can be passed to clearInterval() to stop the periodically executed function from running another time. Here's an example of that:

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

In your example, if you want count2 to have the same value as count, you could use:

var count = 0, count2 = 0;
setInterval(function() {
    // I wrote this on two lines for clarity.
    ++count;
    count2 = count;
}, 1000);
查看更多
ゆ 、 Hurt°
3楼-- · 2019-05-24 07:38

setInterval returns an ID which you can later use to clearInterval(), that is to stop the scheduled action from being performed. It will not be related to the count values in any way.

查看更多
We Are One
4楼-- · 2019-05-24 07:43
var count=0;
function incrementCount(){
    count++;
}
setTimeout("incrementCount()", 1000);
查看更多
登录 后发表回答