DEV Community

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

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.