开发者

storing the value of setInterval

开发者 https://www.devze.com 2023-02-01 00:20 出处:网络
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

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

精彩评论

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