30
Apr
11

JavaScript Sleep


This page describes a simple implementation of a sleep function in javascript.

Java has a Thread.sleep() functionality however there is nothing like this in javascript. In order to obtain this functionality you will need to create a custom function.

This is a simple way to implement a sleep function in JavaScript. It works by implementing an semi-infinite loop. In each iteration it checks and breaks out, if the difference in the start time and the current time is greater than the number of milliseconds specified as the argument.

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

Call the function like this:

sleep(1000); // sleep for 1 second

This is a form of busy waiting… But currently the only way. Please post a comment if you disagree.

Advertisements

2 Responses to “JavaScript Sleep”


  1. June 17, 2011 at 7:04 am

    I agree that this is a form of busy waiting… But, “currently the only way”

    JS is asynchronous, why fire a setTimeout(requiredFunc(), time);

    Better to call it later, than lock up the browser…

  2. 2 kanian77
    June 24, 2011 at 9:38 am

    I agree with vanitylicenseplate. JS being asynchronous, it provides functions such as setinterval and settimeout. Another way is to pass a function around to use as a callback in case the wait is for a function to complete. And as, said earlier sleep would lock the browser. Maybe we may get some kind of context if you share with us the reason why you needed the sleep function?


Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 77 other followers

April 2011
S M T W T F S
« Mar   May »
 12
3456789
10111213141516
17181920212223
24252627282930

Blog Stats

  • 830,829 hits

%d bloggers like this: