Pause JavaScript execution for a specified amount of time using
Promises.
Works elegantly with
async/await
and accepts flexible time formats like '3s'
and '1h'
(any string that can
be parsed by the ms package). Implemented in
TypeScript.
Installation
$ yarn add sleep-ts# or $ npm install --save sleep-ts
Usage
;// orconst sleep = sleep; // With async/await { console; // a number argument is treated as milliseconds, so this will // sleep for 1 second await ; // a string argument is parsed, so this will sleep for 2 seconds await ; console;} // With raw Promises;
Output:
Hello# 3 seconds later World# 1 second later PING# 3 seconds later PONG
Alternatives
- If you don't care about the fancy time format parsing, you can use sleep-promise, which might save you a subdependency on the
ms
package. - Use setTimeout if you're okay with using callbacks.
Other Languages
- C#: Thread.Sleep
- C++: std::this_thread::sleep_for (since C++11; otherwise, check out these methods)
- Go: time.Sleep
- Java: Thread.sleep
- Perl: sleep
- PHP: sleep
- Python: time.sleep
- R: Sys.sleep
- Ruby: sleep
- Rust: std::thread::sleep