Skip to content

Instantly share code, notes, and snippets.

@martinheidegger
Last active April 19, 2017 01:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martinheidegger/5abd8556492afd3c5bfd6f7389d91231 to your computer and use it in GitHub Desktop.
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
#!/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