So it turns out the while loop blocks the event loop in JavaScript, which prevents it from being a viable solution to creating a run loop if you want your application to respond to external / async events.
My question is, what techniques are used to have a "run loop" be infinite / constant but still have high performance and not block the event loop.
I ran a quick test to see the performance of while
, setTimeout(fn, 0)
(browser), and setImmediate(fn)
(node.js).
var x = 1000
var isNode = typeof window == 'undefined'
function a() {
var start = (new Date()).getTime()
var q = 0
function next() {
q++
if (q < x) {
if (isNode) {
setImmediate(next)
} else {
setTimeout(next, 0)
}
} else {
var end = (new Date).getTime()
console.log('a', end - start)
}
}
next()
}
function b() {
var start = (new Date()).getTime()
var q = 0
while (q < x) {
q++
}
var end = (new Date).getTime()
console.log('b', end - start)
}
a()
b()
node.js:
a = 20
b = 0
browser:
a = 5039
b = 0
Is there not a way to do an "infinite while loop" that is as performant as doing a while loop in JavaScript. setImmediate
is much faster than setTimeout
, but it's still a lot slower than the basic while loop.