开发者

Whats wrong with setInterval() and clearInterval() in this javascript function? clearInterval returns undefined

开发者 https://www.devze.com 2023-04-13 00:04 出处:网络
I have the following开发者_如何学Go code: var focusIntervalObj = setInterval(function(){ focusDelayCaused++;

I have the following开发者_如何学Go code:

var focusIntervalObj = setInterval(function(){
            focusDelayCaused++;
            console.log(focusDelayCaused);
        }, 100);

clearInterval(focusIntervalObj);

I am have a firebug installed.

I am expecting this code to log the value of focusDelayCaused.

But when I execute, it doesn't do so, and also the clearInterval() simply returns undefined.

Please guide.


You are setting the interval and clearing it before it fires.

var focusIntervalObj = setInterval(function(){
        focusDelayCaused++;
        console.log(focusDelayCaused);
        clearInterval(focusIntervalObj);
    }, 100);

That might be what you are thinking. Which would be simpler as:

var focusIntervalObj = setTimeout(function(){
        focusDelayCaused++;
        console.log(focusDelayCaused);
    }, 100);


Going on the code above, you're immediately clearing an interval just after you've set it. So it never has a chance to run.

Clearing the interval after some sort of condition has been met rather than immediately after setting it would help.

if (focusDelayCaused>50) {
  clearInterval(focusIntervalObj);
}


If you want some function be executed once and never again, use setTimeout, in your case:

var focusIntervalObj = setTimeout(function(){
            focusDelayCaused++;
            console.log(focusDelayCaused);
        }, 100);
0

精彩评论

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

关注公众号