-
-
Save cowboy/360138 to your computer and use it in GitHub Desktop.
setInterval and setTimeout patterns
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ========================= | |
// SetInterval | |
// ========================= | |
// While not truly accurate, setInterval is still fairly good, time-wise. | |
// Better for things like a "one second tick" but not great for expensive | |
// code executed at small intervals as iterations can "stack". | |
// (ECMAScript 5 strict mode compatible) | |
// First "arbitrary code" execution happens after ~1000ms, subsequent | |
// executions follow suit. | |
setInterval(function(){ | |
console.log(new Date()); // run some arbitrary code | |
}, 1000); | |
// First "arbitrary code" execution is synchronous, subsequent executions | |
// happen every ~1000ms. | |
setInterval((function loopy(){ | |
console.log(new Date()); // run some arbitrary code | |
return loopy; | |
})(), 1000); | |
// ========================= | |
// setTimeout | |
// ========================= | |
// While less accurate time-wise than setInterval, setTimeout allows for | |
// more "breathing room" when executing expensive code at smaller intervals, | |
// as a next iteration will only happen ~1000ms _after_ the arbtrary code is | |
// executed and, not _before_ (like setInterval) | |
// First "arbitrary code" execution is synchronous, subsequent executions | |
// happen every ~1000ms. | |
(function loopy(){ | |
console.log(new Date()); // run some arbitrary code | |
setTimeout( loopy, 1000 ); | |
})(); | |
// First "arbitrary code" execution happens after ~1000ms, subsequent | |
// executions follow suit. | |
(function loopy(){ | |
setTimeout(function(){ | |
console.log(new Date()); // run some arbitrary code | |
loopy(); | |
}, 1000 ); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
One caveat to the
(function foo(){ ... foo(); })()
pattern is that it doesn't work in BlackBerry OS 5.x or earlier, as the code inside the named function expression can't access the the function by name (for whatever reason). So, if you're writing cross-OS mobile JavaScript, you should avoid this pattern.See this jQuery hashchange event issue for a little more information on this issue.