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

11 thoughts on “Javascript – Sleep Function”

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

    Like

  2. 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.
    

    Like

  3. 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.

    Like

  4. 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);}
    }
    

    Like

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.