How to write a synchronous locking method in Javascript?

I am trying to make fun of a method that takes a lot of time to test, but cannot find a good way to do this in Javascript. Any good approaches besides writing a very long loop?

+7
source share
2 answers

How about a loop that checks time ?

function sleep(milliSeconds){ var startTime = new Date().getTime(); // get the current time while (new Date().getTime() < startTime + milliSeconds); // hog cpu until time up } 
+7
source

You can make a synchronous AJAX call to a server that defers a response for a certain amount of time at the request of your script. Note, however, that this method will not work in Firefox since it does not support synchronous AJAX calls.

Just use this simple client-side function:

 function sleep(microseconds) { var request = new XMLHttpRequest; request.open("GET", "/sleep.php?time=" + milliseconds); request.send(); } 

sleep.php -side sleep.php code:

 usleep(intval($_GET("sleep"))); 

Now you can create blocking synchronous functions in JavaScript (with the exception of Firefox) as follows:

 alert("Hello"); sleep(1000000); // sleep for 1 second alert("World"); 
+3
source

All Articles