Skip to content

Instantly share code, notes, and snippets.

@XanderLuciano
Created August 16, 2018 05:48
Show Gist options
  • Save XanderLuciano/f2f6e4f0d7ec93d5b9cc11366fe638bb to your computer and use it in GitHub Desktop.
Save XanderLuciano/f2f6e4f0d7ec93d5b9cc11366fe638bb to your computer and use it in GitHub Desktop.
Useful Javascript & Vue Templates

Async sleep function

Effectively an easy way to call setTimeout() from within an async function.

note: This will only wait at least this many ms before execution continues.

const sleep = ms => new Promise(res => setTimeout(res, ms));

// Usage
await sleep(100);

Make Synchronous Loop Async

// Method 1
async function myAsyncFunction () {
  return new Promise(resolve => {
    let condition = true;
    
    function loop() {
      while (condition) {
        // Do work
      }
      if (requirement) {
        resolve(data);
      } else {
        setTimeout(loop, 0); // continue next cycle
      }
    }
    loop();
  });
}

// Usage
const result = await myAsyncFunction();

Using await sleep

// Method #2
let condition = true;
let progress = 0;
async loop myAsyncFunction() {
  const sleep = ms => new Promise(res => setTimeout(res, ms));
  
  while (condition) {
    await sleep(0); // continue next cycle
    // Do work and update progress
    progress = getProgress;
  }
}

// Usage
await myAsyncFunction();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment