Câu hỏi phỏng vấn Nodejs
Câu hỏi

What is the difference between setTimeout(fn,0) vs setImmediate(fn) ?

Câu trả lời

In Node.js, both setTimeout(fn, 0) and setImmediate(fn) are used to schedule tasks for future execution, but they differ in their execution order within the Node.js event loop.

Execution Order in the Event Loop

  • setTimeout(fn, 0): This function schedules the callback fn to be run after a minimum threshold of 0 milliseconds. However, due to the way the Node.js event loop is structured, this does not guarantee immediate execution. Instead, the callback is placed in the Timer Queue and will execute after all the I/O events callbacks and any timers that are due to execute[1][2][3][4]. The actual execution might be delayed depending on the other operations that are queued in the event loop.

  • setImmediate(fn): This function is specifically designed to execute a script once the current poll phase of the event loop completes, and all I/O events have been processed. The callback fn is placed in the Check Queue, which is processed immediately after the I/O operations[1][2][3][4]. This typically means it will execute before any timers if scheduled within an I/O cycle, as it is prioritized right after I/O callbacks.

Practical Differences

  • Priority: setImmediate(fn) is generally given priority over setTimeout(fn, 0) when both are called within an I/O cycle (e.g., within an I/O callback). This is because the Check Queue (where setImmediate callbacks are placed) is processed right after handling I/O events, but before the Timer Queue (where setTimeout(fn, 0) callbacks are placed)[1][2][3][4].

  • Use Cases:

    • **`setTimeout(fn,...
middle

middle

Gợi ý câu hỏi phỏng vấn

junior

What does Promisifying technique mean in Node.js?

middle

When would you use global variables in Node.js? Are they always bad?

middle

What is chai and chai-http in Node.js userland?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào