Skip to content

Instantly share code, notes, and snippets.

@irazasyed
Created April 14, 2013 11:57
Show Gist options
  • Select an option

  • Save irazasyed/5382444 to your computer and use it in GitHub Desktop.

Select an option

Save irazasyed/5382444 to your computer and use it in GitHub Desktop.
JavaScript: Sleep Functions (Sleep in Milliseconds and Seconds)
/* ============================================================
| :=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);
}
@JamshadAhmad
Copy link

@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

Copy link

ghost commented Sep 9, 2018

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.

@turbopixel
Copy link

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