Is there any way to make JavaScript to wait for 0.01 milliseconds? I'd like to place it inside a for loop, such that the time interval between each iteration is 0.01 milliseconds.
-
1There's `setTimeout()`. You can't make a JavaScript thread "wait" however. – Pointy Sep 14 '15 at 14:07
-
20.01 millisecond ? Do you realize how quick that is... I believe the you can't have a time unit smaller that 1 millisecond. – VVV Sep 14 '15 at 14:10
-
2The [spec](https://html.spec.whatwg.org/multipage/webappapis.html#timers) also specifies a minimum interval of 4ms. – swornabsent Sep 14 '15 at 14:10
-
4If you intend to run JavaScript with 10 μsec resolution you are going to be disappointed. – Phylogenesis Sep 14 '15 at 14:11
-
3Don't you mean 0.01 seconds? – GolezTrol Sep 14 '15 at 14:12
-
Possible duplicate of [Sleep in Javascript - delay between actions](http://stackoverflow.com/questions/758688/sleep-in-javascript-delay-between-actions) – Ryan Sep 30 '16 at 23:07
4 Answers
You can't make JS "wait". You can only defer operations to a later time, and the engine continues to execute, only pulling in deferred operations when the engine is doing nothing.
The closest JS would have to a "waiting loop" is setInterval(fn, 0)
. But it's never really zero delay. Most engines cap it at 4ms. Plus, delays are "minimums", not guarantees. They're not accurate.

- 117,725
- 30
- 181
- 234
One method would be to create an interval timer, and only have that run so many times:
functionToRun(){
if (counter<1000) {
//keep running, and do stuff
}
counter++
}
var counter=0;
var functionToRun = setInterval("functionToRun();",100);
//100 is milliseconds
This will start your function right away. But it will only fire 1000 times. That's the basic idea. You can play with it to do what you need it to do.

- 4,666
- 2
- 16
- 30
Here's the function
setInterval(function(){...},0.01);
But you can't really pause the thread.

- 518
- 6
- 18
setTimeout(yourfunctionhere,0.01);
Here is a fiddle https://jsfiddle.net/Pufflegamerz_Studios/g9Lwfh2r/
setTimeout(function() {
alert("Hello!")
}, 0.001)