


get (uri ) )Īs one might expect, this code makes a request to the GitHub API to fetch my user data. But from a semantical point of view, there's a lot to be improved.Understanding JavaScript’s Execution Modelīefore we get going, it’s important to make sure we understand JavaScript’s execution model correctly.Ĭonsider the following Ruby code: require 'net/http' require 'json' call the rest of the code and have it execute after 3 secondsįrom a technical point of view, that's the end of the story. call the first chunk of code right away all the stuff you want to happen after that pauseĬonsole.log('Blah blah blah blah extra-blah') The idea is sketched in this StackOverflow answer: You wrap the code you want to execute later in a function, which is executed by a setTimeout() call. Multi-threading may be a useful metaphor, but in reality the only way to simulate it is to use setTimeout() or setInterval(). It's important to keep in mind there's only one thread in node.js. Pausing the "main" thread without stopping the "secondary" threads The sleep library pauses precisely this event loop. There's only one thread with an event loop. Only there's no such thing as a secondary thread in node.js. I wanted to delay the main thread for a second, but I didn't want to stop the secondary thread to process the result of the REST call. If you've initiated a REST call, it won't be processed until the sleep period is over. That may be great for debugging, but it stops everything. The library follows a "stop the world" approach. It offers methods to stop the execution of your node.js application for a couple of seconds, milliseconds, or microseconds.Īt second glance, you'll see the large print on the npm site. At first glance, it's exactly the library you're looking for. the one you install with npm install sleep). I'm talking about the library called sleep (i.e. In the JavaScript worlds, there's a library for everything. Luckily, modern node.js allows you to simulate the feature so you hardly notice the difference. The free plan only allows one access per second, so I had to make my node.js program pause a second between two accesses.Īs it turns out, you can't do that in node.js. In my case, is was OpenStreetMap that forced me to go a slower pace. However, in rare cases, you need to slow down.
