Delayed execution in JavaScript

Thread sleep equivalent in JavaScript

Not very often, but from time to time you need to slow down your code. Most of the time the reason for that is that you need to test some long execution, mostly external source call. This important as you cannot simulate delayed response if you are developing everything locally.

If you have access to the remote call backend you can simulate delay on it's back-end using simple sleep of the executing thread, but in case you cannot do that as if you are invoking let's say Twitter, Facebook or Instagram API, you need to simulate day on you client side. Unfortunately JavaScript is still not so advanced so sleep of the executing thread is not an option in JavaScript. Insetad we have to do some workarounds.

Simple thing can be done by making your code busy doing nothing for some time :) using simple empty loop:

function sleep(interval) {
  var start = new Date().getTime();
  for (var i = 0; i < Number.MAX_VALUE; i++) {
    if ((new Date().getTime() - start) > interval){
      break;
    }
  }
}
    

This can be done even simplier usng while loop instead of for loop:

function sleep(interval) {
  var start = new Date().getTime();
  while((new Date().getTime() - start) <= interval){}
}
    

The previous two approaches are not so elegant, as they are basically junk code, but it well servers for testing and you can easily switch it off by just commenting the line of the function call.

However, there is a more elegant way, but does not work exactly the same way.

setTimeout(function() {
    console.log("1 second interval expired");
  }, 1000);
    

JavaScript's setTimeout will schedule some code execution but will not stop the code executing where it stopped. That is first big difference. The second one is that it is not so easy to switch it off once you finish the testing as it is not only one line that needs to be put under comments. If you know any better or more elegant way to achieve this, feel free to post your comments.

 

 

 

Disclaimer

Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.


About the author

DEJAN STOJANOVIC

Dejan is a passionate Software Architect/Developer. He is highly experienced in .NET programming platform including ASP.NET MVC and WebApi. He likes working on new technologies and exciting challenging projects

CONNECT WITH DEJAN  Loginlinkedin Logintwitter Logingoogleplus Logingoogleplus

.NET

read more

SQL/T-SQL

read more

Umbraco CMS

read more

PowerShell

read more

Comments for this article