OneBite.Dev - Coding blog in a bite size

sleep in javascript

Code snippet for how to how to sleep in javascript with sample and detail explanation

Understanding how to utilize sleep function in JavaScript can be a valuable skill for any developer. This function allows the execution of a JavaScript program to pause for a specified amount of time.

Code snippet for sleep function

Here’s a simple code snippet to illustrate how a sleep function can be implemented in JavaScript:

function sleep(miliseconds) {
   var start = new Date().getTime();
   for (var i = 0; i < 1e7; i++) {
     if ((new Date().getTime() - start) > miliseconds){
       break;
     }
   }
 }
 
console.log('Before calling sleep function');
sleep(1000);
console.log('After calling sleep function');

Code Explanation for sleep function

Let’s step by step understand how this sleep function works in Javascript.

  1. Function Declaration: First of all, we have declared a function “sleep” which takes one parameter, miliseconds. This parameter will determine the pause time for our sleep function.
function sleep(miliseconds) {
  1. Current Time Calculation: We utilize JavaScript’s Date object to get the current time in milliseconds since 1st January 1970, which is stored in the “start” variable.
var start = new Date().getTime();
  1. For Loop: Next, there is a ‘for’ loop which runs indefinitely until the condition inside the ‘if’ statement becomes true.
for (var i = 0; i < 1e7; i++) {
  1. If Condition: Inside the ‘if’ condition, we continuously check whether the current time minus the start time is greater than the input miliseconds. If it is, we break out of the loop, thus implementing the sleep or pause functionality.
if ((new Date().getTime() - start) > miliseconds){
       break;
     }
  1. Print Statements: And finally we have two console.log statements before and after the call to the sleep function just to show where the sleep function execution started and ended.
console.log('Before calling sleep function');
sleep(1000);
console.log('After calling sleep function');

In conclusion, while JavaScript doesn’t have a traditional sleep function like some other languages, creating a custom sleep function assists to pause or delay the execution of subsequent JavaScript code, which can be useful in some scenarios.

javascript