Execute script after specific delay using JavaScript

JavascriptSettimeout

Javascript Problem Overview


Is there any JavaScript method similar to the jQuery delay() or wait() (to delay the execution of a script for a specific amount of time)?

Javascript Solutions


Solution 1 - Javascript

Just to add to what everyone else have said about setTimeout: If you want to call a function with a parameter in the future, you need to set up some anonymous function calls.

You need to pass the function as an argument for it to be called later. In effect this means without brackets behind the name. The following will call the alert at once, and it will display 'Hello world':

var a = "world";
setTimeout(alert("Hello " + a), 2000);

To fix this you can either put the name of a function (as Flubba has done) or you can use an anonymous function. If you need to pass a parameter, then you have to use an anonymous function.

var a = "world";
setTimeout(function(){alert("Hello " + a)}, 2000);
a = "Stack Overflow";

But if you run that code you will notice that after 2 seconds the popup will say 'Hello Stack Overflow'. This is because the value of the variable a has changed in those two seconds. To get it to say 'Hello world' after two seconds, you need to use the following code snippet:

function callback(a){
	return function(){
		alert("Hello " + a);
	}
}
var a = "world";
setTimeout(callback(a), 2000);
a = "Stack Overflow";

It will wait 2 seconds and then popup 'Hello world'.

Solution 2 - Javascript

There is the following:

setTimeout(function, milliseconds);

function which can be passed the time after which the function will be executed.

See: Window setTimeout() Method.

Solution 3 - Javascript

Just to expand a little... You can execute code directly in the setTimeout call, but as @patrick says, you normally assign a callback function, like this. The time is milliseconds

setTimeout(func, 4000);
function func() {
    alert('Do stuff here');
}

Solution 4 - Javascript

If you really want to have a blocking (synchronous) delay function (for whatsoever), why not do something like this:

<script type="text/javascript">
	function delay(ms) {
		var cur_d = new Date();
		var cur_ticks = cur_d.getTime();
        var ms_passed = 0;
		while(ms_passed < ms) {
            var d = new Date();  // Possible memory leak?
            var ticks = d.getTime();
            ms_passed = ticks - cur_ticks;
            // d = null;  // Prevent memory leak?
        }
	}
    
    alert("2 sec delay")
    delay(2000);
    alert("done ... 500 ms delay")
    delay(500);
    alert("done");
</script>

Solution 5 - Javascript

You need to use setTimeout and pass it a callback function. The reason you can't use sleep in javascript is because you'd block the entire page from doing anything in the meantime. Not a good plan. Use Javascript's event model and stay happy. Don't fight it!

Solution 6 - Javascript

You can also use window.setInterval() to run some code repeatedly at a regular interval.

Solution 7 - Javascript

To add on the earlier comments, I would like to say the following :

The setTimeout() function in JavaScript does not pause execution of the script per se, but merely tells the compiler to execute the code sometime in the future.

There isn't a function that can actually pause execution built into JavaScript. However, you can write your own function that does something like an unconditional loop till the time is reached by using the Date() function and adding the time interval you need.

Solution 8 - Javascript

If you only need to test a delay you can use this:

function delay(ms) {
   ms += new Date().getTime();
   while (new Date() < ms){}
}

And then if you want to delay for 2 second you do:

delay(2000);

Might not be the best for production though. More on that in the comments

Solution 9 - Javascript

why can't you put the code behind a promise? (typed in off the top of my head)

new Promise(function(resolve, reject) {
  setTimeout(resolve, 2000);
}).then(function() {
  console.log('do whatever you wanted to hold off on');
});

Solution 10 - Javascript

The simple reply is:

setTimeout(
    function () {
        x = 1;
    }, 1000);

The function above waits for 1 second (1000 ms) then sets x to 1. Obviously this is an example; you can do anything you want inside the anonymous function.

Solution 11 - Javascript

I really liked Maurius' explanation (highest upvoted response) with the three different methods for calling setTimeout.

In my code I want to automatically auto-navigate to the previous page upon completion of an AJAX save event. The completion of the save event has a slight animation in the CSS indicating the save was successful.

In my code I found a difference between the first two examples:

setTimeout(window.history.back(), 3000);

This one does not wait for the timeout--the back() is called almost immediately no matter what number I put in for the delay.

However, changing this to:

setTimeout(function() {window.history.back()}, 3000);

This does exactly what I was hoping.

This is not specific to the back() operation, the same happens with alert(). Basically with the alert() used in the first case, the delay time is ignored. When I dismiss the popup the animation for the CSS continues.

Thus, I would recommend the second or third method he describes even if you are using built in functions and not using arguments.

Solution 12 - Javascript

delay function:

/**
 * delay or pause for some time
 * @param {number} t - time (ms)
 * @return {Promise<*>}
 */
const delay = async t => new Promise(resolve => setTimeout(resolve, t));

usage inside async function:

await delay(1000);

Or

delay(1000).then(() => {
   // your code...
});

Or without a function

new Promise(r => setTimeout(r, 1000)).then(() => {
   // your code ...
});
// or
await new Promise(r => setTimeout(r, 1000));
// your code...

Solution 13 - Javascript

I had some ajax commands I wanted to run with a delay in between. Here is a simple example of one way to do that. I am prepared to be ripped to shreds though for my unconventional approach. :)

//	Show current seconds and milliseconds
//	(I know there are other ways, I was aiming for minimal code
//	and fixed width.)
function secs()
{
	var s = Date.now() + ""; s = s.substr(s.length - 5);
  return s.substr(0, 2) + "." + s.substr(2);
}

//	Log we're loading
console.log("Loading: " + secs());

//	Create a list of commands to execute
var cmds = 
[
	function() { console.log("A: " + secs()); },
	function() { console.log("B: " + secs()); },
	function() { console.log("C: " + secs()); },
	function() { console.log("D: " + secs()); },
	function() { console.log("E: " + secs()); },
  function() { console.log("done: " + secs()); }
];

//	Run each command with a second delay in between
var ms = 1000;
cmds.forEach(function(cmd, i)
{
	setTimeout(cmd, ms * i);
});

// Log we've loaded (probably logged before first command)
console.log("Loaded: " + secs());

You can copy the code block and paste it into a console window and see something like:

Loading: 03.077
Loaded: 03.078
A: 03.079
B: 04.075
C: 05.075
D: 06.075
E: 07.076
done: 08.076

Solution 14 - Javascript

As other said, setTimeout is your safest bet
But sometimes you cannot separate the logic to a new function then you can use Date.now() to get milliseconds and do the delay yourself....

function delay(milisecondDelay) {
   milisecondDelay += Date.now();
   while(Date.now() < milisecondDelay){}
}

alert('Ill be back in 5 sec after you click OK....');
delay(5000);
alert('# Im back # date:' +new Date());

Solution 15 - Javascript

The simplest solution to call your function with delay is:

function executeWithDelay(anotherFunction) {
    setTimeout(anotherFunction, delayInMilliseconds);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNiyazView Question on Stackoverflow
Solution 1 - JavascriptMariusView Answer on Stackoverflow
Solution 2 - JavascriptAbhinavView Answer on Stackoverflow
Solution 3 - JavascriptPolsonbyView Answer on Stackoverflow
Solution 4 - JavascriptMario WernerView Answer on Stackoverflow
Solution 5 - JavascriptPatrickView Answer on Stackoverflow
Solution 6 - JavascriptrcoupView Answer on Stackoverflow
Solution 7 - JavascriptnarasiView Answer on Stackoverflow
Solution 8 - JavascriptChristofferView Answer on Stackoverflow
Solution 9 - JavascriptAl JoslinView Answer on Stackoverflow
Solution 10 - JavascriptLucaView Answer on Stackoverflow
Solution 11 - JavascriptDougView Answer on Stackoverflow
Solution 12 - JavascriptZuhair TahaView Answer on Stackoverflow
Solution 13 - JavascriptJohnnyIVView Answer on Stackoverflow
Solution 14 - JavascriptJavaSheriffView Answer on Stackoverflow
Solution 15 - JavascriptJackkobecView Answer on Stackoverflow