Back to library
🛠️Utilitiesjavascriptbeginner

Sleep/Delay Function

Promise-based delay function for async code

asynctimingutilities

Code

1// Basic sleep function
2const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
3
4// Usage with async/await
5async function example() {
6  console.log('Starting...');
7  await sleep(2000); // Wait 2 seconds
8  console.log('Done!');
9}
10
11// With abort support
12function sleepWithAbort(ms) {
13  let timeoutId;
14  const promise = new Promise((resolve) => {
15    timeoutId = setTimeout(resolve, ms);
16  });
17  
18  promise.cancel = () => clearTimeout(timeoutId);
19  return promise;
20}
21
22// Usage with cancellation
23const delay = sleepWithAbort(5000);
24// Cancel if needed
25delay.cancel();

Quick Tips

  • Click the "Copy" button to copy the code to your clipboard
  • This code is production-ready and can be used in your projects
  • Check out related snippets below for more examples

Build Your Own Snippet Library

Organize your team's code snippets with Snippetly. Share knowledge and boost productivity across your organization.