Skip to content

Instantly share code, notes, and snippets.

@lukemorton
Created December 8, 2011 10:55
Show Gist options
  • Save lukemorton/1446707 to your computer and use it in GitHub Desktop.
Save lukemorton/1446707 to your computer and use it in GitHub Desktop.
Syncronous (safe) setInterval()
// Syncronous setInterval
// Usage:
// var interval = new SyncInterval(function () {
// console.log('bob');
// }, 500);
// interval.stop();
// Written by Luke Morton, Richard Willis
function SyncInterval(fn, wait, scope) {
var t = this;
wait = wait || 1000;
t.timeout = setTimeout(function () {
fn.call(scope);
t.timeout = setTimeout(arguments.callee, wait);
}, wait);
}
SyncInterval.prototype.stop = function () {
clearTimeout(this.timeout);
};
@lukemorton
Copy link
Author

Hot shit, just noticed you used arguments.callee! That's awesome didn't know about that! Thanks @badsyntax

@badsyntax
Copy link

Aye very cool :)

@badsyntax
Copy link

Hey @drpheltright, it might be worth reverting the arguments.callee call, and instead naming the function. (It appears arguments.callee is deprecated and won't work in strict mode, see http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/)

t.timeout = setTimeout(function timer() {
    fn.call(scope);
    t.timeout = setTimeout(timer, wait);
}, wait);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment