How to Wait 1 Second in JavaScript?

by Vincy. Last modified on October 20th, 2023.

Wait is there every aspect of human life. Let’s get philosophical for a moment! For every good thing in life, you need to wait.

“There’s no such thing as failure – just waiting for success.” – John Osborne

Like in life, wait in programming is also unavoidable. It is a tool, that you will need some day on desperate situations. For example, a slider, a fading animation, a bouncing ball, you never know.
View Demo

In this tutorial, we will learn about how to wait one second in JavaScript? One second is an example. It could be a “5 seconds” or any duration your code needs to sleep before continuing with operation.

Refer this linked article to learn about PHP sleep.

Wait

JavaScript wait 1 second

I have used the good old setTimeout JavaScript function to wait. It sleeps the processing for the milliseconds duration set. Then calls the callback function passed.

You should put the code to execute after wait inside this callback function. As for the wait duration 1000 millisecond is one second. If you want to wait 5 seconds, then pass 5000.

This code will be handy if you are creating a news ticker like scroll animation.

	var testWait = function(milliseconds) {
		console.log('Before wait');
		setTimeout(function() {
			console.log('After wait');
		}, milliseconds);
	}

	testWait(1000);

JavaScript wait 1 second for promise

If you are using a modern browser, then you can use the below code. Modern means, your browser should support ES6 JavaScript standard.

In summary, you need support for JavaScript Promise. Here we use the setTimeout function. It resolves the promise after the defined milliseconds wait.

// Promise is available with JavaScript ES6 standard
// Need latest browsers to run it
const wait = async (milliseconds) => {
    await new Promise(resolve => {
        return setTimeout(resolve, milliseconds)
    });
};

const testWait = async () => {
    console.log('Before wait.');
    await wait(1000);
    console.log('After wait.');
}

testWait();

JavaScript wait 1 second in loop

If you want to wait the processing inside a loop in JavaScript, then use the below code. It uses the above Promise function and setTimeout to achieve the wait.

If yours is an old browser then use the first code given above for the wait part. If you need to use this, then remember to read the last section of this tutorial. In particular, if you want to “wait” in a mission critical JavaScript application.

const wait = async (milliseconds) => {
    await new Promise(resolve => {
        return setTimeout(resolve, milliseconds)
    });
};

const waitInLoop = async () => {
    for (let i = 0; i < 10; i++) {
        console.log('Waiting ...');    	
        await wait(1000);
        console.log(i);
    }
    console.log("The wait is over.");
}

waitInLoop();

JavaScript wait 1 second in jQuery

This is for people out there who wishes to write everything in jQuery. It was one of the greatest frontend JavaScript libraries but nowadays losing popularity. React is the new kid in the block. Here in this wait scenario, there is no need to look for jQuery specific code even if you are in jQuery environment.

Because you will have support for JavaScript. You can use setTimeout without any jQuery specific constructs. I have wrapped setTimeout in a jQuery style code. Its old wine in a new bottle.

// if for some strange reason you want to write
	// it in jQuery style
	// just wrapping the setTimout function in jQuery style

	$.wait = function(callback, milliseconds) {
		return window.setTimeout(callback, milliseconds);
	}

	$.wait(function() {
		$("#onDiv").slideUp()
	}, 1000);

Cancel before wait for function to finish

You may have to cancel the wait and re-initiate the setTimeout in special scenarios. In such a situation use the clearTimeout() function as below. Go through the next section to know about such a special wait scenario.

let timeoutId = setTimeout(() => {
	   // do process 
	})
	// store the timeout id and call clearTimeout() function
	// to clear the already set timeout
	clearTimeout(timeoutId);

Is the wait real?

You need to understand what the JavaScript wait means. When the JavaScript engine calls setTimeout, it processes a function. When the function exits, then a timeout with defined milliseconds is set. After that wait, then JavaScript engine makes the callback.

When you want to know the total wait period for next consecutive call. You need to add the time taken by your function to process to the wait duration.

So that is a variable unit. Assume that the function runs for five seconds. And the setTimeout wait duration is one second. Then the actual wait will become six seconds for the next call.

If you want to precise call every five seconds, then you need to define a self adjusting setTimeout timer.

You should account the time taken to process, then reduce the time from the wait milliseconds. Then cancel the current setTimeout. And start new setTimeout with the new calculated time.

That’s going to be tricky. If you are running a mission critical wait call, then that is the way to go.

For example, general UI animations, the above basic implementations will hold good. But you need the self adjusting setTimeout timer for critical time based events.

setInterval will come closer for the above scenario. Any other UI process running in main thread will affect setInterval’s wait period. Then your one second wait may get converted to 5 seconds wait. So, you should define a self adjusting setTimeout wait for mission critical events.
View Demo

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “How to Wait 1 Second in JavaScript?”

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page