DEV Community

Cover image for Wait for it: Implementing a sleep() function in JS

Wait for it: Implementing a sleep() function in JS

Daniel Sasse on June 03, 2021

In my last blog entry, I had created a visualizer to model an approach to solving a Leetcode algorithm problem. I had planned to create a second en...
Collapse
 
vittostack profile image
Vitto Rivabella

Interesting post! Just wrote some multithreading stuff on Python and is definitely similar to Js :)

Collapse
 
martixy profile image
Martin Ninov

I can't reply to your question about the GIL below. (?)
JS does not have a GIL. It does not need a GIL. It is single-threaded in general. Though there do exist things like workers which allow limited, but true multi-threading capabilties.

Collapse
 
dsasse07 profile image
Daniel Sasse

Thank you Martin!

Collapse
 
dsasse07 profile image
Daniel Sasse

Your multithreading article was really interesting. Definitely some similarities with threading.join(). Thank you for reading!

Collapse
 
vittostack profile image
Vitto Rivabella

Yeah, one quick question, does Js implements something like the Python GIL?

Thread Thread
 
dsasse07 profile image
Daniel Sasse • Edited

From my understanding of GIL from your post, there is something similar. JS uses a single threaded call stack to resolve functions so the most recently invoked function must be resolved before the previous one. Function execution proceeds line by line. When utilizing setTimeout and setInterval like I described above, it actually adds the callback function passed to those to a separate call stack that has priority at during run time. When the timer is up, these functions execute before returning to the main call stack.

This is why I couldn't just use a timeout by itself, because the main thread would proceed and finish execution without waiting for the timeout stack to execute and return its value. Hope that helps!

Thread Thread
 
tuanfrontend profile image
Eden Tuấn

Hello

Collapse
 
tuanfrontend profile image
Eden Tuấn

Hello

Thread Thread
 
tuanfrontend profile image
Eden Tuấn

Hello

Thread Thread
 
tuanfrontend profile image
Eden Tuấn

Hello

Collapse
 
peerreynders profile image
peerreynders • Edited

This is why I couldn't just use a timeout by itself, because the main thread would proceed and finish execution without waiting for the timeout stack to execute and return its value.

This statement confuses me.

The main thread runs the event loop and typically in the browser the event loop doesn't exit and in node JS the event loop doesn't exit when there are still pending asynchronous tasks.

Given your sample code when you run action() a Promise value is immediately returned before any rounds are posted. So strictly speaking from your point of view the "main thread has finished" (though of course it hasn't because the event loop continues to process the scheduled code).
Now granted the returned promise doesn't resolve until all the rounds are posted - but that would imply that your event loop only exits once all promises were settled.

That would mean that you only need a single promise that doesn't resolve until all the rounds are posted.

So while it is certainly educational to implement something like sleep(), I would think twice before using it primarily because sleep() is a concept from synchronous code bases.

Typically in an asynchronous environment "scheduling tasks" is a more appropriate mental model, e.g.:

function roundWork(i, delay) {
  console.log(`Round ${i + 1}`);
  console.log(`Waiting for ${delay}ms`);
}

function postWork() {
  console.log('Posting');
}

function launchAction(delay, rounds, done) {
  // start the round
  roundTask(0);

  // function declarations hoist to the top
  function roundTask(i) {
    if (i < rounds) {
      roundWork(i, delay);
      setTimeout(postTask, delay, i);
    } else {
      setTimeout(done);
    }
  }

  function postTask(i) {
    postWork();
    roundTask(i + 1);
  }
}

new Promise((done, _reject) => {
  launchAction(500, 4, done);
}).then(() => {
  console.log('complete');
});
Enter fullscreen mode Exit fullscreen mode

In order of increasing priority:

For details on the event loop see In The Loop - JSConf.Asia and the blog post Tasks, microtasks, queues and schedule.

Specifications for future scheduling API's are being actively developed.

The point being - the sooner one adopts organizing code by tasks that can be scheduled in an asynchronous environment like JavaScript the better. Sticking to a more "synchronous" style of predominantly controlling the (main thread) flow is ultimately limiting (even though it initially may seem more familiar).

Collapse
 
dsasse07 profile image
Daniel Sasse

Hi peerreynders, thank you for your insight and for the resources you shared. I will definitely check them out to see how they can be applied. For the purpose of the visualizer that inspired this post, the sleep action is allowing me the opportunity to create the visual model for the data structure before mutating the structure in the next iteration.

Collapse
 
benjaminwfox profile image
Ben Fox

Cool use-case, nice explanation!

Collapse
 
imagineeeinc profile image
Imagineee • Edited

thanks, really needed this, and I learnt a bit on promises