问题描述
事实证明,如果您希望应用程序响应外部/异步事件,则阻止它成为创建运行循环的可行解决方案。
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.
我跑了一个快速测试,看的表现,而
, setTimeout (fn,0)
(浏览器), setImmediate(fn)
(node.js)。
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()
节点。 js:
a = 20
b = 0
浏览器:
a = 5039
b = 0
没有办法做一个无限循环,就像做一个while循环一样高效在JavaScript中。 setImmediate
比 setTimeout
快得多,但它仍然比基本的while循环慢很多。
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.
推荐答案
这样的事情可行:
var THRESHOLDCOUNT = 10000
var THRESHOLDTIME = 15
function loop(fn) {
var start = Date.now()
var changed = false
var x = 0
while (!changed) {
while (x < THRESHOLDCOUNT) {
x++
fn()
}
var end = Date.now()
changed = end - start > THRESHOLDTIME
}
// make room for external events.
setImmediate(loop)
}
这篇关于创建“运行循环”的最佳解决方案在JavaScript中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!