Saturday, August 20, 2011

Javascript - pausing script flow ( sleep )

Sometimes it happens, that I need to PAUSE the flow of my script. And I mean pause, with capital letters, because these times a simple setTimeout would not help.

There is a very nice, browser independent method to do this:

1. Create a synchronous AJAX call
2. On the server side call the "sleep( [sec] )" function

To speak in code, this is the javascript (jQuery) part of it:

function pause(millisec) {
	jQuery.ajax({
		type: "GET",
		url: "index.php",
		data: {
			task: 'pause',
			pauseMillisec: millisec
		},
		async: false
	});
}


And this is the PHP part:

<?php 
if( $_GET["task"] == "pause" ) {
	sleep( $_GET["pauseMillisec"]/1000 );
} 
?>

That's all folks.. isn't it easy? :)

Feel free to share your thoughts with me.

No comments:

Post a Comment