Javascript – Sleep Function

There is no sleep()/wait() function in Javascript. The setTimeout() is not exactly a sleep()/wait() function as it behaves like creating another thread for the scheduled task.

By Google, i got a manual sleep()/wait() function. Try the following code.

*Update @ 2011-07-22: This function drains CPU usage and may throw error in IE. Use with extreme caution. Thanks SmartCoder for pointing out the issue. =)

<html>
  <head>
    <script type="text/javascript">
      /**
       * Delay for a number of milliseconds
       */
      function sleep(delay) {
        var start = new Date().getTime();
        while (new Date().getTime() < start + delay);
      }
    </script>
  </head>
  <body>
    <h1>Eureka!</h1>
      <script type="text/javascript">
        alert("Wait for 5 seconds.");
        sleep(5000)
        alert("5 seconds passed.");
      </script>
  </body>
</html>

 

Done =)

Reference: JavaScript Sleep Function

About these ads

11 thoughts on “Javascript – Sleep Function

  1. Smart Coder

    This is not good practice, as it will drain cpu usage, and cause IE to throw errors if longer than 5 seconds.

    Reply
    1. ykyuen Post author

      That’s true. i have added a reminder on the post. Thanks for pointing out the problem. =)

      Reply
  2. usn

    Here’s a possible alternative that may work in some cases:

    function Sleep(){return(function(){alert("I'm awake");});} // Does nothing.	
    var goToSleep = Sleep(); // Create the object.
    alert("Go to sleep");
    setTimeout(goToSleep, 5000); // Go to sleep for n milliseconds.
    
    Reply
    1. usn

      It could also be done like this:

      function Sleep(){} // Does nothing.
      setTimeout(Sleep, 5000); // Go to sleep for n milliseconds.
      
      Reply
  3. mherasika

    Hi,

    If you need sleep function – you can send sync request to server …
    function sleep(milliseconds) {
    //code here for you SYNC request to server /*asp.net or php*/
    }

    it’s works,browser block all events until http response.

    Reply
  4. Carlos

    Test

    var begin;
    
    function test()
    {
    	try
    	{
    		var seconds = 3;
    		test1();
    		setTimeout("alert('check')", (seconds * 500));
    		//wait(seconds);
    		//sleep(seconds);
    		delay(seconds, "test2");
    		test2();
    	}
    	catch(e)
    	{
    		if(e.number != -9999)
    		{
    			alert(e.description);
    		}
    	}
    }
    
    function test1()
    {
    	begin = (new Date()).getTime();
    	alert("begin " + begin);
    }
    
    function test2()
    {
    	var end = (new Date()).getTime();
    	alert("end " + end + " =&gt; " + ((end - begin) / 1000));
    }
    
    function delay(time, fnReturn)
    {
    	var fnOnError = window.onerror;
    	window.onerror = function(){return false;};
    
    	setTimeout("returnDelay('" + fnReturn + "', '" + fnOnError + "')", time * 1000);
    	throw {"description" : "Delay stop processing",
    	       "number" : -9999};
    }
    
    function returnDelay(fnReturn, fnOnError)
    {
    	window.onerror = fnOnError;
    	eval(fnReturn + "()");
    }
    
    function sleep(time, isBegin)
    {
    	var deep = 10;
    
    	if(isBegin == null || isBegin)
    	{
    		time *= deep;
    	}
    
    	if(time &gt; 0)
    	{
    		var delay = 1000 / deep;
    		var begin = (new Date()).getTime();
    		while((new Date()).getTime() &lt; begin + delay){void(0);}
    		sleep(--time, false);
    	}
    }
    
    function wait(time)
    {
    	time *= 1000;
    	var begin = (new Date()).getTime();
    	while((new Date()).getTime() &lt; begin + time){void(0);}
    }
    
    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

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