Last active
April 19, 2017 01:17
-
-
Save martinheidegger/5abd8556492afd3c5bfd6f7389d91231 to your computer and use it in GitHub Desktop.
An explanatory script to illustrate the timings of intervals and the event loop
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
#!/usr/bin/env node | |
const foreverTick = (fn) => { | |
// Note: Using process.nextTick instead of setImmediate will result in an endless loop! | |
const ticker = () => { | |
// stopForever is a nice trick for a stoppable forever function | |
const stopForever = fn() | |
if (!stopForever) { | |
setImmediate(ticker) | |
} | |
} | |
setImmediate(ticker) | |
return ticker | |
} | |
var calledThisTick = {} | |
var ticks = 0 | |
foreverTick(() => { | |
ticks += 1 | |
calledThisTick = {} | |
}) | |
setInterval(function () { // foo! | |
console.log('Foo called! bar=' + calledThisTick.bar, "baz=" + calledThisTick.baz, "ticks-since-last-interval=" + ticks) | |
ticks = 0 | |
calledThisTick.foo = true | |
}, 250) | |
foreverTick(() => { // bar! | |
if (calledThisTick.baz) { | |
console.log('This can never occur, because baz will always be added after bar') | |
process.exit(1) | |
} | |
calledThisTick.bar = true | |
}) | |
foreverTick(() => { // bar! | |
if (calledThisTick.bar != true) { | |
console.log('This can never occur, because bar will always be executed before baz') | |
process.exit(1) | |
} | |
if (calledThisTick.foo) { | |
console.log('This can never occur, because all ticks are always executed in order, and the cleanup always executes before this tick') | |
process.exit(1) | |
} | |
calledThisTick.baz = true | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment