Tech Study

JavaScript Sleep() function

JavaScript sleep

To pause execution in any programming language for a set period of time, programmers use the JavaScript sleep() function, which is also possible in JavaScript. Unlike other programming languages, JavaScript doesn’t allow the execution of a built-in JavaScript sleep() function. It allows users to use the Promise object to deal with all asynchronous behavior.

Along with the JavaScript Promise, some other functions and techniques can prove to be helpful to execute a sleeping kind of functionality in JavaScript, like the async await functions. The syntax of sleep: sleep(delayTime in milliseconds).then(() => {

// code to be executed

})

Users can use the JavaScript sleep function to pause the current thread execution for a fixed time in Milliseconds. Then, the thread doesn’t lose its power as the examiner and continues its execution. JavaScript programmers use the JavaScript sleep() function with the await or async to attain a pause in the program implementation.

<script> 

   function sleep(milliseconds) 
   return new Promise(resolve => setTimeout(resolve, milliseconds)); 

   } 

   async function function1() 
   document.write('We are going to learn sleep'); 

   for (let i = 1; i <=5 ; i++) {     

      await sleep(2000)
      document.write( i + ". " + "Hey, this is JavaScript sleep function" + " " + "</br>"); 

   } 

   } 

   function1(); 

</script>

We used the JavaScript sleep() function with the async await functionalities in the below code snippet. Moreover, we use a JS function named “function1(),” and we define it with arbitrary statements. At first, the textbook “We’re going to learn sleep” is displayed on the screen once the function starts. Moreover, the JavaScript sleep() function pauses the operation of function function1() for four seconds. After four seconds, the JavaScript engine displays the subsequent text “Hey, this is JavaScript sleep function” on the screen and reprises it until the loop terminates. The function will iterate the text five times on the screen with a pause of four seconds on the iteration of the loop.

Java Final keyword

Introduction : java final keyword The final keyword present in Java programming language is generally used for restricting the user. …

Read more

C++ Memory Management: new and delete

C++ Memory Management We know that arrays store contiguous and the same type of memory blocks, so memory is allocated …

Read more