Skip to content

Instantly share code, notes, and snippets.

@joeperpetua
Last active May 6, 2023 13:38
Show Gist options
  • Save joeperpetua/c8af5edf4e62b41f28c52778f3846334 to your computer and use it in GitHub Desktop.
Save joeperpetua/c8af5edf4e62b41f28c52778f3846334 to your computer and use it in GitHub Desktop.
Async sleep function with unit parameters for JavaScript.
const sleep = async (time, unit) => {
switch(unit){
case 'ms':
return new Promise(resolve => setTimeout(resolve, time));
break;
case 's':
return new Promise(resolve => setTimeout(resolve, time*1000));
break;
case 'm':
return new Promise(resolve => setTimeout(resolve, time*60000));
break;
case 'h':
return new Promise(resolve => setTimeout(resolve, time*3600000));
break;
default:
throw new Error(`Sleep unit measure not recognized.\nSupported: ms, s, m, h.\nGiven: ${unit}`);
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment