js sleep code example

Example 1: javascript sleep

const sleep = (milliseconds) => {
  return new Promise(resolve => setTimeout(resolve, milliseconds))
}

/*Use like so*/

async function timeSensativeAction(){ //must be async func
  //do something here
  await sleep(5000) //wait 5 seconds
  //continue on...
}

Example 2: javascript sleep

function sleep(milliseconds) {
  const date = Date.now();
  let currentDate = null;
  do {
    currentDate = Date.now();
  } while (currentDate - date < milliseconds);
}

console.log("Hello");
sleep(2000);
console.log("World!");

Example 3: javascript wait 1 second

setTimeout(function(){ 
    console.log("Ready")
}, 1000);

Example 4: sleep function javascript

How to get a JavaScript sleep function

First, you must sacrifice JS to the gods of asynchronous programming.
Then, go to grepper and ctrl c + v some code with no idea how to use it.
Give up.
Realise you didnt need it in the first place.
Die inside a little.
Realise you should have stayed with python.
Learn Java out of frustration.

Example 5: js sleep

// Sync version
function sleep(sleepDuration){
    var now = new Date().getTime();
    while(new Date().getTime() < now + sleepDuration){ /* do nothing */ } 
}

Example 6: js sleep

const sleep = require('util').promisify(setTimeout);