Monday, July 20, 2020

How To Sleep With Javascript

How To Sleep With Javascript




If you’re a .NET developer you are probably familiar with the Thread.Sleep() method, which allows you to pause further execution of your code until a defined period of time has passed. 

Unfortunately there is no direct equivalent for sleep with javascript, but there are several alternatives to get similar results, but they will probably require you to modify your code slightly to take advantage of it. 

setTimeout() is the most common solution. 
It allows you to execute some code after a set time.

The format is as follows:

  1. setTimeout(function(){
  2. //Do stuff after the set wait time
  3. },timeInMillisecondsToWait)

Once problem with this approach is that the javascript simply won’t pause execution until after the wait time, it will just carry on processing everything else and whenever the timeout you’ve set has elapsed it will execute the code within the setTimeout function. 
For Example:

  1. function test2() {
  2.  
  3. alert("1");
  4.  
  5. setTimeout(function () {
  6. alert("2");
  7. }, 10000);
  8. alert("3");
  9. }

alert(“1”) will execute, skip over alert(“2”), execute alert 3, then wait 10 seconds (From the point that setTimeout was hit) then finally execute alert(“2”). 
This is probably not what you would have wanted. 
In order to make sure that your code executes in the correct order, you’ll need to add the rest of your code within the body of the setTimeout method, which as you can imagine, could get messy if you have code which relies on additional delays.

  1. function test3() {
  2. alert("1");
  3.  
  4. setTimeout(function () {
  5. alert("2");
  6. alert("3");
  7. }, 10000);
  8. }

Your best bet is to encapsulate your code into functions where appropriate, making it look a bit cleaner without sacrificing functionality.

If you enjoyed this article, please consider giving it a +1


Online Course

React Native Chat App with Firebase - Firestore Course 2020


This course is for every programmer who wants to learn mobile application development and want to increase their skills to the next level.

Online Course


This is a Beginner to Advanced course and perfectly suitable for anyone interested to learn jQuery effects and animations for their web projects. If you have basic knowledge of HTML, CSS, and JavaScript then you're good to go. After finish, you'll learn 12 really cool effects that you can use in your web projects. Moreover, using this knowledge you'll be able to do more interesting effects on your own. 

No comments:

Post a Comment

The 3 Most Popular Front-end Frameworks Compared

  There’s an outsized number of front-end frameworks available today, each with different strengths and weaknesses. This makes it tricky to ...