Created
April 14, 2013 11:57
-
-
Save irazasyed/5382444 to your computer and use it in GitHub Desktop.
JavaScript: Sleep Functions (Sleep in Milliseconds and Seconds)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* ============================================================ | |
| | :=Sleep (Delay) | |
| =============================================================== */ | |
| // Milliseconds | |
| function sleep_ms(millisecs) { | |
| var initiation = new Date().getTime(); | |
| while ((new Date().getTime() - initiation) < millisecs); | |
| } | |
| // Seconds | |
| function sleep_s(secs) { | |
| secs = (+new Date) + secs * 1000; | |
| while ((+new Date) < secs); | |
| } |
Instead of having a new Date instance, why not just use "static" method now, like Date.now(). Static methods use less memory than creating a new instance everytime, especially when checking the while loop.
My solutions (after 6 years):
function waiting(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
async function test(){
console.log("start");
await waiting(600);
console.log("600ms later");
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@irazasyed This is not CPU friendly sleep. Control will be stuck in this loop and processor won't be able to process any other task meanwhile.
Selected answer here might be better than this solution.
https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep