setTimeout
works fine, I don't consider it a hack.
(setTimeout
工作正常,我不认为这是一个hack。)
But there's also queueMicrotask
, which might sound more suited to your purpose - it queues a microtask which'll run as soon as all other synchronous Javascript has finished executing:(但是还有一个queueMicrotask
,听起来可能更适合您的目的-它将一个微任务排队,该微任务将在所有其他同步Javascript完成执行后立即运行:)
function doA(callback) { console.log("Do A") queueMicrotask(callback); } function doB() { console.log("Do B") } function doC() { console.log("Do C") } doA(doC) doB()
It's basically equivalent to Promise.resolve().then(callback)
.
(它基本上等效于Promise.resolve().then(callback)
。)
Note that an immediate setTimeout
queues a macrotask (one which will run once the event loop gets around to processing the next message , which may take a few milliseconds) - in contrast, queueMicrotask
and Promise.resolve.then
queues a microtask, which will run basically immediately after other synchronous JS is finished.
(请注意,立即setTimeout
一个宏任务排队(该宏任务将在事件循环处理下一条消息时运行 ,该任务可能需要几毫秒的时间)-与此相反, queueMicrotask
和Promise.resolve.then
将一个微Promise.resolve.then
排队,该宏将运行基本上在其他同步JS完成后立即执行 。)
Also keep in mind that queueMicrotask
, while supported in Node, is not exactly widely supported in browsers yet, so if you want to use it on a public-facing website, make sure to include a polyfill (or use the Promise.resolve
method).
(另外请记住,虽然queueMicrotask
支持的queueMicrotask
尚未在浏览器中得到完全支持,所以如果要在面向公众的网站上使用它,请确保包含Promise.resolve
(或使用Promise.resolve
方法) 。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…