开发者

The best way to let a function run several times with setInterval()?

what's the best way to have a function executed several times with setInterval()? The problem with my attempt here is, that the variable "timer" is not known when clearing Interval ...

...
        if (counter.hasClass("superWarn")){
            var timer = setInterval(toggleCharCount(), 500);
    }开发者_运维问答
...

function toggleCharCount() {
    if(typeof toggleCharCount.i == 'undefined'){
        toggleCharCount.i = 0;
    }
    toggleCharCount.i++;
    $('#twCharCount').toggle();
    if (toggleCharCount.i>=4){
        window.clearInterval(timer);
        toggleCharCount.i = 0;
    }
}

Thx for any advice ...


why dont u pass the timer into the callback?

...
        if (counter.hasClass("superWarn")){
            var timer = setInterval(function(){toggleCharCount(timer)}, 500)
    }
...

function toggleCharCount(timer) {
    if(typeof toggleCharCount.i == 'undefined'){
        toggleCharCount.i = 0;
    }
    toggleCharCount.i++;
    $('#twCharCount').toggle();
    if (toggleCharCount.i>=4){
        window.clearInterval(timer);
        toggleCharCount.i = 0;
    }
}


I cannot see your complete javascript code, nut it seems the variable timer is not in the global scope. If you move 'timer' into globalscope, the function 'toglleCharCount()' will get an access.


function tester(asd){
  alert(timer);
}
var timer = setInterval(function(timer){
  tester(timer)
}, 5000);

working example http://jsfiddle.net/EEAAC/


1) from my tests, if you name a function as a variable, it can't be good:D :

var foo = {i:'my number'};
function foo(){
    alert(foo.i);
}

either foo will be interpreted as an object, either as a function, but it cannot hold two different values at the same time.
2) when you send a parameter as a function call (setTimeout(myFunction(),t)), the function gets executed when setTimeout is being defined. The right way to do is to send a function, not a function call, or a string that will be evaluated :

setTimeout(myFunction,t);
// or
setTimeout("myFcuntion()",t);
// or the best way :
setTimeout(function(){myFunction();},t);

3) timer is declared in a different scope than the clearInterval function is, so when when you want to clear the interval, you do not have any reference to the interval itself, because timer is undefined. You should eigher delcare them both in the same scope, or you can deeclare timer as global (withouth the var keyword), thus making timer visible in the global scope, where any other 3d party can see it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜