storing the value of setInterval

烈酒焚心 提交于 2019-12-07 23:59:38

问题


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


回答1:


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



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/4532696/storing-the-value-of-setinterval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!