public
Last active

setInterval run once, then keep running

  • Download Gist
gistfile1.js
JavaScript
1 2 3 4 5
setInterval((function () {
console.log(new Date()); // run some arbitrary code
return arguments.callee; // here be the magic
})(), 1000);
// ^---- and that runs the function, and the return val is assign to the interval

Awesome, I've always wondered if that was possible.

an ecmascript5 strict mode safe version, without arguments.callee:

setInterval((function fn() {
    console.log(new Date()); // run some arbitrary code
    return fn;               // here be the magic
})(), 1000);
// ^---- and that runs the function, and the return val is assign to the interval

Yeah, it should be noted that, as per Paul's comment - es5 doesn't support arguements.callee - in fact, I think Paul's is cleaner code since you've got a named function to help with debugging and performance.

I have a gist fork of this one with some setInterval and setTimeout patterns in it.

isn't this going to create memory leaks in IE with the named function expression?

How does a named function help with performance?

Also, I prefer the arguments approach better, since it's very useful when creating, say, a library. If I pass the arguments object to the library, the lib has got context of both caller and callee with a simple API. In ES5, the API would get complicated. This has been my biggest gripe with ES5.

Accessing the arguments object is very slow.
http://www.jspatterns.com/arguments-considered-harmful/
http://webreflection.blogspot.com/2010/02/arguments-callee-call-and-apply.html

@getify, i'm aware of the NFE scope leaking bugs in IE, but not any memory leaks..

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.