Could not select database
JavaScript sleep

DevCheater.com - javascript sleep

Have you ever needed the sleep command in JavaScript? Usually you can use the existing setTimeout(), clearTimeout() and setInterval() to accomplish what you want and in those cases you should use the native functions. But if you really need the sleep or wait statement lets go through the options and see what code might work the best.

Of course you can always skip to the conclusion.

What should the requirements of the sleep method be? I think power basic described it the most clearly as:
Pause the current thread of the application for a specified number of milliseconds (mSec), allowing other processes (or threads) to continue.
Power Basic sleep() - Win32 Sleep() - Java Thread.sleep()

The different ways in which we will make a javascript sleep function are:

JavaScript sleep by loop

The most basic way would be something like this:

<script type="text/javascript">
// bad implementation
function sleep(milliSeconds){
	var startTime = new Date().getTime(); // get the current time
	while (new Date().getTime() < startTime + milliSeconds); // hog cpu
}
</script>

We are using a while loop on line 3 that continually evaluates the current time against the time when we should stop blocking. This loop will run as fast as the browser will let it all the while using up valuable cpu resources. Checking the time might not seem like much but doing it thousands (or tens of thousands) of times per second make a noticeable performance impact on your computer (try it and watch your cpu meter). This code will "pause" your thread but will also use all the resources your computer will give it. javascript sleep by loop example

Analysis for javascript sleep loop

This implementation does block the running javascript but it also consumes all the CPU resources it can while sleeping and freezes all other javascript in the page (in all browsers tested).

JavaScript sleep by Java Applet

One solution to the problem has ended up being in a Java Applet. Since you can communicate between javascript and java applets and that communication is blocking we can use Java's Thread.sleep() method (which when run uses almost no resources).


<applet code="DevCheater.class" name="devCheater" id="devCheater" mayscript="true" height="1" width="1"></applet>

<script type="text/javascript">

	function sleep(milliSeconds){
		// runs Java Applets sleep method
		document.devCheater.sleep(milliSeconds); 
	}

</script>

This version might look simpler then the last one but that is because some of the code is hidden away in the DevCheater.class Java file. On line 1 you can see an applet tag that utilizes my DevCheater.class Java class, this is what loads the Java program into the page so that it can be accessed by any javascript on it. Now this is where the bad news comes in. Not all browsers will allow other javascript to run while waiting for the Java sleep method to finish. Essentially sleeping all javascript on the page... See for your self JavaScript sleep by java applet example

Analysis for Java Applet

We do block the running javascript and no extra CPU resources are used while sleeping. This method does not freeze all other javascript in the page (except when using Chrome). Unfortunately it does require a java plug-in to be installed for their browser which limits its usefulness.

JavaScript sleep by Flash

If we try using Java then why not adobe flash too. In this attempt I created a flash application that has a method called very unoriginally "flashSleep()". I now use javascript to call my flash method and pass in the number of milliseconds to sleep. But unfortunately this method also results in a freeze for most browsers I tested.

<script type="text/javascript">

	function sleep(milliSeconds){
		// call sleep method in flash
		getFlashMovie("flashSleep").flashSleep(milliSeconds);
	}

	function getFlashMovie(movieName){
		// source: http://kb2.adobe.com/cps/156/tn_15683.html
		var isIE = navigator.appName.indexOf("Microsoft") != -1;
		return (isIE) ? window[movieName] : document[movieName];
	}

</script>
	<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="50" height="50" id="flashSleep" align="middle">
	<param name="allowScriptAccess" value="sameDomain" />
	<param name="allowFullScreen" value="false" />
	<param name="movie" value="flashSleep.swf" />
	<param name="quality" value="high" />
	<param name="bgcolor" value="#ffffff" />	
	<embed src="flashSleep.swf" quality="high" bgcolor="#ffffff" width="50" height="50" name="flashSleep" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
	</object>

Analysis for Flash

Using adobe flash is no better then the rest when it comes to freezing. For that reason this method should not be used. javascript sleep by flash example

JavaScript sleep by XMLHttp

Another way is to use server communication with XMLHttp.

<script type="text/javascript">

function sleep(milliSeconds){
	var resource;
	var response;
	if(typeof ActiveXObject == 'undefined'){
		resource = new XMLHttpRequest();
	}
	else{
		// IE
		resource = new ActiveXObject("Microsoft.XMLHTTP");
	}

	try{
		resource.open('GET', 'sleep.php?milliSeconds=' + milliSeconds, false);
		resource.send(null);
		response = resource.responseText; // JavaScript waits for response
	}
	catch(e){
		alert(e);
	}
	
	return true;
}
	
</script>
<?PHP
	$milliSeconds = intval($_REQUEST['milliSeconds']);
	if($milliSeconds > 60*1000){
		// limit server abuse
		$milliSeconds = 10;
	}
	
	usleep($milliSeconds * 1000); // note: usleep is in micro seconds not milli
	echo "done";
?>
Here we try to load another file from the server called sleep.php and send the the number of milli seconds we want the sleep to be. The PHP script then uses that value in its native usleep function. But again some browsers will freeze all javascript when this is run. javascript sleep by XMLHttp example

Note: Any type of server software could be used in the place of Apache and PHP. IIS and ASP for example.

Analysis for XMLHttp

This does block the running javascript and no extra CPU resources are used on the user’s computer but it does add extra load on your server. As well this implementation does freeze all other javascript on the page in all browsers tested. The added server connections makes this method unacceptable for any use because it is bound to max out the servers allowed connections, essentially creating your own DDoS attacks on your server :-(

Conclusion

As you can see from the results listed below in almost every case trying to implement a sleep function in javascript has the unwanted side effect of freezing the entire browser. And for that reason no implementation should be used. Instead the native setTimeout() or setInterval() functions should always be choosen.

select * from `SleepStats` order by `browserName`, `browserVersion`, `osName`, `osVersion`, `version`, `freeze`
1046: No database selected
Browser Operating System Implementation Freeze
(This list is automatically generated from the "Test my Browser" buttons on each examples web page. So please contribute to this list by testing your browser with each of our examples. Currently 0 tests are included.)

P. S. The reason that JavaScript freezes the browser while sleeping is because it only runs as a single thread.

P. S. S. There are a few other javascript sleep implementations that could be used (Workers for example) but I have choosen to only provide examples that will run on all major browsers. These may freeze the browser but still run on them all.


Newsletter and Contact Form

Please signup for our newsletter in order to be notified whenever updates are made to this site.
As always, any corrections, comments or suggestions are greatly appreciated.

Newsletter
Enter code
Your Name
Your Email
Subject
Your Message

© Copyright 2016 All Rights Reserved

DevCheater software is licensed under LGPL 3 and free of charge.