开发者

Call an anonymous function defined in a setInterval

I've made this code:

window.setInterval(function(){ var a = doStuff(); var b = a + 5; }, 60000)

The actual contents of the anonymous function is of course just for this small example as it doesn't matter. What really happens is a bunch of variables get created in the scope of the function itself, because I don't need/want to pollute the global space.

But as you all know, the doStuff() function won't be called until 60 seconds in the page. I would also like to call the function right now, as soon as the page is loaded, and from then on every 60 seconds too.

Is it somehow possible to call the function without copy/pasting the inside code to right after the setInterval() line? As I said, I don't want to pollute the global space with useless variables that aren't needed outside the funct开发者_运维知识库ion.


You can put your callback function in a variable, and wrap up everything in a self-invoking anonymous function:

(function () {
    var callback = function() { 
        var a = doStuff(); 
        var b = a + 5; 
    };

    callback();

    window.setInterval(callback, 60000);
})();

No pollution.


This is possible without creating global variables as well:

setInterval((function fn() {
 console.log('foo'); // Your code goes here
 return fn;
})(), 5000);

Actually, this way, you don’t create any variables at all.

However, in Internet Explorer, the fn function will become accessible from the surrounding scope (due to a bug). If you don’t want that to happen, simply wrap everything in a self-invoking anonymous function:

(function() {
 setInterval((function fn() {
  console.log('foo'); // Your code goes here
  return fn;
 })(), 5000);
})();

Credit to Paul Irish for sharing this trick.


Edit: Answer updated with some more information, thanks to bobince.


yet another solution:

(function() { 
    var a = doStuff(); 
    var b = a + 5; 
    window.setTimeout(arguments.callee, 60000);
})();

This uses timeout instead of interval so that it can run the first time and then run it's self again after a timeout.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜