How to make a pause (sleep) in JavaScript? Need an analog of sleep() from other languages
Hello everyone! I'm a beginner in JavaScript, switched from Python, and encountered a problem. In Python, I often used `time.sleep(2)` to pause program execution, for example, when working with APIs to avoid exceeding request limits, or for console animations.
In JavaScript, I tried to write something similar:
```javascript
function sleep(ms) {
// ?????
}
console.log("Starting");
sleep(2000);
console.log("2 seconds passed");
```
But I can't find a built-in `sleep()` function. I tried using `setTimeout`, but it doesn't stop code execution, it just delays the callback call. As a result, the message "2 seconds passed" is printed immediately, not after 2 seconds.
Please advise how to properly implement a delay in JavaScript? I need the code to execute sequentially.
No answers yet.
Log in to leave an answer