JavaScript is asynchronous and non-blocking in nature. This means that operations do not naturally pause or wait before proceeding to the following line of code. In everyday applications, developers usually face some circumstances where they need to pause the code, mainly when working with UI updates, rate-limiting API calls, or automated testing.
Overview
Different methods to make JavaScript wait for 1 second:
- setTimeout(): Executes a function after a specified delay without blocking the rest of the code.
- async/await with Promise: Wraps setTimeout in a Promise to create a pause using await, allowing sequential execution.
- Promise with then(): Uses Promises and .then() chaining to wait and execute code after the delay.
- Inline Promise with async/await: Directly writes a Promise inside an async function for simple, one-off waits.
- Callout (custom wait function): Creates a reusable wait function using Promise, commonly used in browser automation.
- Sleep using timers/promises (Node 15+): Uses the native setTimeout from Node’s timers/promises module for cleaner sleep in Node.js.
- Delay NPM package: A third-party package that provides promise-based delays with additional features like cancellation (Node.js only).
This article will help in learning about the various approaches to implementing wait time in JavaScript, using basic techniques and simple code examples.
Practical Use Cases for Waiting in JavaScript
Here are practical use cases for waiting in JavaScript:
- API Rate Limiting and Throttling: Sometimes APIs have limits on how many requests can be made in a short time. Adding a wait between requests helps avoid getting blocked or receiving errors.
- Retrying Failed Requests: If a network request fails (due to timeout, server error, etc.), waiting for a short period before retrying increases the chance of success without overwhelming the server.
- Polling for Status or Updates: When performing background operations like data processing or uploads, it’s common to check the status at regular intervals with a wait in between each check.
- Delaying Actions for Animations: In user interfaces, waiting ensures that transitions or animations (like fade-ins or fade-outs) complete before the next action takes place, creating a smooth user experience.
- Simulating Delays in Testing: While testing, especially in end-to-end tests or UI tests, simulated waits can help mimic real user behavior or slow server responses for better test coverage.
- Timers in Games or Applications: Games and some interactive apps use waiting to introduce delays for turns, countdowns, level transitions, or to pace game events.
- Waiting for Elements to Load: On dynamic websites, some elements might load after a delay. Waiting ensures that scripts or interactions occur only when the necessary elements are present on the page.
Read more: How to Enable File Downloads in JavaScript?
Different Approaches to Make JavaScript Wait for 1 Second
Like other programming languages, JavaScript does not have a built-in sleep() method. However, there are different techniques that can be used to simulate waiting. It is possible to achieve a 1-second wait in JavaScript by implementing the techniques given below.
1. Using setTimeout() to Wait
One of the most used methods for delaying the execution of JavaScript is setTimeout(). It executes a callback after the specified time duration.
SetTimeout is one of the simplest ways to stop the main thread in JavaScript.
Overview: A callback is executed by the setTimeout() function after a specified period of time (in milliseconds).
Code Example:
console.log("Starting line"); setTimeout(function(){console.log('Code waits for 1 second')}, 1000); console.log("Ending line");
Output:
Explanation:
The function inside setTimeout() is executed after 1000 milliseconds, i.e., 1 second. However, the code does not stop there and it continues to execute the next line. Hence, “Ending line” is printed in the log before “Code waits for 1 second“.
2. Using async/await
Using the async/await syntax simplifies the handling of asynchronous operations.
Overview: SetTimeout() can be wrapped in a Promise and used with async/await to freeze execution in order to make it function in a blocking way.
Code Example:
function waitOneSecond() { return new Promise(resolve => setTimeout(resolve, 1000)); } async function executeWithWait() { console.log("Starting line"); await waitOneSecond(); console.log("Code waits for 1 second"); console.log("Ending line"); } executeWithWait();
Output:
Explanation:
The code execution waits at that line until the Promise resolves as the setTimeout() appears inside the Promise and await is used. Hence, “Code waits for 1 second” is printed in the log before “Ending line“.
Read More: Top 9 JavaScript Testing Frameworks
Limitations of setTimeout() in Asynchronous Code
The following are the limitations to be considered when using the SetTimeout() method.
- Synchronous functions cannot be paused.
- Blocking loops like for() or while() cannot be delayed using this method without rewriting them as async.
- It does not return a value or context after the delay.
- It can lead to faulty tests when overused without having a proper event waiting in test automation.
3. Using Promises for Better Control
Promises offer a systematic way for implementing delays with better readability and reliability, specifically for automated test cases or complicated workflows.
Overview: Asynchronous operations can be handled more efficiently and easily with Promises in JavaScript.
Code Example
console.log("Starting line"); new Promise(resolve => setTimeout(resolve, 1000)) .then(() => { console.log("Code waits for 1 second"); console.log("Ending line"); });
Output
Explanation
- console.log(“Starting line”); statement is executed first.
- A new Promise is created, and inside it, setTimeout() waits for 1000 milliseconds (1 second) before calling the resolve().
- After the specified time is over, resolve() is implemented, and the .then() block is executed.
- console.log(“Code waits for 1 second”) and console.log(“Ending line”) statements are executed inside the .then() after the pause.
Read More: JavaScript Unit Testing Tutorial
4. Using Inline Promise to Wait
Developers can regulate flow and chaining delays more easily with Inline Promises.
Overview: By inlining the Promise into an async function, the efforts of creating a separate wait function can be reduced.
Code Example:
async function test() { console.log("Starting line"); await new Promise(resolve => setTimeout(resolve, 1000)); console.log("Code waits for 1 second"); console.log("Ending line"); } test();
Output:
Explanation:
The code example uses the Promise inline method, which is useful for linking delays, without creating a reusable function.
Read More: How to use JavascriptExecutor in Selenium
5. Using Callout to Wait
In browser automation, a callout refers to when JavaScript is executed directly in the browser window using executeScript. It is especially helpful for Selenium wait functions.
Overview: It is a function that can be used as a reusable delay tool by returning a Promise-based callout.
Code Example:
function wait(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function callOut() { console.log("Step 1: First Line"); await wait(1000); console.log("Step 2: This log is printed after 1 second"); } callOut();
Output:
Explanation:
This code pauses for 1 second inside the browser. It is commonly used in automation testing.
6. Using Sleep with Timers in Node 15+
‘timers/promises’ can be used to add setTimeout as a promise to delay the execution when using Node 15+.
Overview: Instead of using a single promise to block the execution, the native setTimeout function is implemented here as a promise.
Code Example (Node.js):
const { setTimeout } = require('timers/promises'); async function sleepDemo() { console.log("Starting line"); await setTimeout(1000); console.log("Code waits for 1 second"); console.log("Ending line"); } sleepDemo();
Output:
Explanation:
The above code is a more effective method of waiting one second in JavaScript, especially Node.js because it makes use of native code. This is useful for any application using sleep in Node.js.
7. Using Delay NPM Package to Wait
The delay package indicates that it is used to delay a promise for a specific amount of time.
Overview: The delay package provides extensive control and cancellation methods together with delay functionality for Node applications.
Prerequisite:
Download and install the delay package with the help of npm.
Code Example:
const delay = require('delay'); async function run() { console.log("Starting line"); console.log("Code waits for 1 second"); await delay(1000); console.log("Ending line"); } run();
Output:
Explanation:
The code above is very similar to the previous example, but here the delay package from NPM is used in place of setTimeout from timers/promises.
Why choose BrowserStack to Test Waiting in JavaScript?
Testing wait logic in JavaScript requires a real-world environment where dynamic content, network latency, and rendering delays can affect execution. BrowserStack Automate offers a robust and scalable solution for testing how delays and waits behave across real browsers and devices, ensuring consistency and reliability.
Key Reasons to Use BrowserStack:
- Real Device Testing: Detect the real-time user behavior delays by testing the JavaScript code with waits on real devices and browsers rather than emulators.
- Cross-Browser Support: Validate the result of setTimeout(), Promises, or async/await-based waits in various browsers such as Chrome, Safari, Firefox, and Edge.
- Selenium & JS Framework Integration: Use WebDriver + JavaScript to quickly add wait logic to automation code.
- Custom Script Execution: Use executeScript() to run JS directly in the browser console to analyze the result of delays in user interface flow.
- Parallel Testing: Run the tests in different environments at the same time to speed up the time-based tests.
- Visual Debugging Tools: Examining the logs, screenshots, and video recordings can help in determining whether the wait times are too short, too long, or ineffective.
Conclusion
JavaScript code requires the implementation of intended waits in order to handle asynchronous processes, enhance user experience, and stabilize test flows.
Developers have access to many ways to make the code wait, starting from basic methods such as setTimeout() to more complex techniques like Promises, async/await, and making use of packages like delay.
Whether it’s automation testing, UI interaction, or API blocking, it’s the situation that determines the best wait strategy that can be implemented. BrowserStack Automate gives customers the ability to collaborate and debug with a variety of logging tools for an infinite number of users.
In addition, BrowserStack Automate also makes it easier to validate these wait mechanisms in actual browsers, allowing a quicker and more dependable development process.