Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Sleep in JavaScript

via: https://stackoverflow.com/a/39914235/102401

Example with external function:

Code

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function demo() {
  console.log('Taking a break...');
  await sleep(2000);
  console.log('Two seconds later, showing sleep in a loop...');

  // Sleep in loop
  for (let i = 0; i < 5; i++) {
    if (i === 3)
      await sleep(2000);
    console.log(i);
  }
}

demo();

Example with sleep inside as one-liner

Code

async function clock_updater() {
    for (let ticker = 0; ticker <= 5;  ticker += 1) {
        await new Promise(r => setTimeout(r, 2000));
        document.getElementById('timer').innerHTML = ticker;
    }
}

clock_updater();

Also:

Code

const { performance } = require('perf_hooks');

const delay = async (ms) => new Promise(resolve => setTimeout(resolve, ms));

const testSuite = async (func, arg) => {
   const t0 = performance.now();

   await func();

   const t1 = performance.now();

   console.log(t1 - t0);
}

const FuncToTest = async () => {
   await delay(10000);
   console.log("FuncToTest");
}

testSuite(FuncToTest)

- Must be in an async function