How to Make JavaScript Sleep or Wait | Built In

Submit
builtin.com

How to Make JavaScript Sleep or Wait | Built In

AI summary of the linked article

This tutorial explains that JavaScript has no built-in sleep() function and that setTimeout() does not pause code between successive lines when called in a sequence, because each call queues asynchronous code that runs after the same delay. It presents two workarounds: a custom sleep function built from a Promise, await and async with setTimeout(), and staggered timeouts such as 1000, 2000 and 3000 milliseconds. The article notes that the custom sleep function can only be called from async functions and must be used with await, and that it works in loops. The author prefers the staggered-timeout approach, which requires tracking or guessing the timeout values in a variable.

No comments yetWhat caught your eye? Start the discussion.