Reputation: 715
I have studied about the event loop in Node.Js, it work in asynchronous and non-blocking manner to process the request. Is there any way so that we can block the execution of event loop?
Upvotes: 10
Views: 10763
Reputation: 13620
Event loop runs on a thread so any call that blocks the thread, like an infinite loop, or a sync file operation, or a blocking network call, will block the event loop.
You can imagine the event loop as first in first out callback queue, if one function call is stuck, subsequent calls will wait for it to finish.
You can also block the event loop by infinitely queuing a new task to the end using setTimeout or setInterval functions.
Upvotes: -1
Reputation: 707328
There are lots of ways to block the event loop. Some ways block it just for awhile (like using synchronous file I/O) and some ways block it forever.
For example, this blocks it forever:
let flag = false;
setTimeout(() => {
// this callback never gets called
// because event loop is blocked
flag = true;
}, 1000);
while (!flag) {
console.log("still waiting")
}
// never get here
The issue is that the while()
loop runs until the flag
changes value. As long as that while loop is running, the event loop is blocked. There's a setTimeout()
that wants to fire in 1 second, but it can't actually call its callback until the interpreter gets back to the event loop. But, it won't get back to the event loop until the while()
loop is done. It's a deadlock which results in an infinite loop and the event loop is permanently blocked.
The setTimeout()
can't call its callback until the while
loop is done and the while
loop won't finish until the setTimeout()
runs its callback. Deadlock, infinite loop.
This blocks it for awhile while all the file operations are going on and all the processing of the files:
setTimeout(() => {
// this doesn't get to run until all the synchronous file I/O
// finishes in the code below, even though the timer is set
// for only 10ms
console.log("finally got to run the timer callback");
}, 10);
let files = some array of files;
for (let file of files) {
let data = fs.readFileSync(file);
let lines = data.split("\n");
for (let line of lines) {
// do something
}
}
Upvotes: 20