I'm trying to mock out a method which takes a long time for testing purposes but can't find a good way to do this in Javascript. Any good approaches besides writing a very long for loop?
3 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's up
}
6 Comments
Abdullah Jibaly
Nice. Pretty obvious in hindsight.
Aadit M Shah
This may cause the JavaScript engine to block other threads (browsers like Firefox < 4.0 will not allow the user to switch tabs or do anything else). Ultimately the browser will notice this and terminate your script. Not a good idea.
Abdullah Jibaly
Works in Chrome, that's all I care about. This is obviously not going into any deployed code :)
Joseph
@AaditMShah the OP just wanted something that acts like sleep. He didn't mention about what should happen while doing so.
Alexander Mills
this is not a good solution, at least not compared to Java's way of dealing with synchronizing code, but maybe it's a limitation of javascript
|
You could make a synchronous AJAX call to a server which defers the response by a certain amount of time as requested by your script. Note however that this method won't work in Firefox as it doesn't support synchronous AJAX calls.
Just use this simple function on the client side:
function sleep(microseconds) {
var request = new XMLHttpRequest;
request.open("GET", "/sleep.php?time=" + milliseconds);
request.send();
}
The code for sleep.php on the server side:
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");
1 Comment
Kevin Seifert
This will burn up a socket connection for an extended period of time though. These are limited. Unless you are using node.js (or some asynchronous framework) it may have scaling issues.
sleep(milliseconds). It's harder to figure out how big the loop needs to be but nothing trial and error can't fix.