
Only by reducing the number of iterations from 10⁷ to 10⁵, it completed after 2:23 minutes! (If you wonder, passing 1, instead of 0, as the delay parameter to setTimeout makes no difference - more on this later) Unfortunately, the cost of this solution is too high: we can see that the CPU is at about ~10%, so it seems it doesn’t work hard enough on the computation, which practically takes forever to complete (didn’t have enough patience to see it happen). So let’s start with a simple Express server:įinally, the server remains responsive during the heavy computation. You can play with the code bellow by cloning

First, let’s block the Node.js Event-Loop!Įxamples below use Node 10.9.0 on an Ubuntu 18.04 VM with 4 cores, running on a MacBook Pro 2017 I’ll do my best to share the various questions I had, and share the answers I’ve found in various great articles, some fun experimentation and digging. Plenty of valuable information already exists about the Node.js Event-Loop, but it took me time find the answers for the specific questions I wanted to ask. I believe it’s important that as many Node developers will have this knowledge too - which led me to writing this article. When I tried to fix the situation, I realized how little I actually knew about the event-loop behavior and gained some realizations that at first surprised me and some fellow developers I shared this with. I recently stumbled upon a real event-loop blocking scenario here at Snyk. This is a known and challenging limitation of Node and is also nicely explained in the docs. There is a single main thread (a.k.a the Event-Loop) that executes all these callbacks, and thus the callbacks should be quick to complete as all other pending callbacks are waiting for their turn. In vanilla JavaScript - we can use the built-in setTimeout() function to "sleep"/delay code execution: setTimeout( function ( ), 1000) Ĭonst timeout2 = setTimeout(printMessage, 2000) Ĭonsole.A typical Node.js app is basically a collection of callbacks that are executed in reaction to various events: an incoming connection, I/O completion, timeout expiry, Promise resolution, etc.

In this short guide, we’ll learn how to wait in JavaScript - or rather, how to sleep/delay code execution, using the setTimeout() function. Note: Delaying Code Execution is colloquially known as "sleeping" or less commonly as "waiting".
