开发者

storing the value of setInterval

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 seInterv开发者_Go百科al() method


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


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.


var count=0;
function incrementCount(){
    count++;
}
setTimeout("incrementCount()", 1000);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜