将回调直接排队到事件队列中

Queue a callback directly into an event queue

在javascript中,有没有办法将回调函数直接放入事件队列中,而不是将 0 作为第二个参数的 setTimeout?

在浏览器中你可以使用requestAnimationFrame or requestIdleCallback:

requestAnimationFrame(() => console.log('Browser is repainting'));

requestIdleCallback(() => console.log('Browser has run out of things to do'));

在Node.js中你可以使用process.nextTick:

process.nextTick(() => console.log('Next tick in the event loop'));

注意:requestIdleCallback 在回答这个问题时是相当新的,因此 check browser compatibility 在您的应用程序中使用它之前。