204

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)?

15 Answers 15

246

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'.

0
196

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.

4
  • 3
    It's not a expression that is executed it's a function. @Marius' answer illustrates that.
    – pedrofurla
    Oct 27, 2012 at 3:45
  • 123
    this is not a delay, it's a fork. Delay should work in same thread.
    – DragonLord
    Oct 31, 2012 at 20:09
  • 14
    This will immediately execute function_reference. To "work" (asynchronously) it should be stated as: setTimeout(function () { MethodToCall(); }, 1000); Nov 17, 2014 at 19:39
  • 7
    I want to point out that we're talking about JavaScript; bringing up "threads" or that it should work "synchronously" may be true technically and semantically but don't really fit within the context of JavaScript, considering there really is no way to achieve a delay with either of those methods (you don't create "threads" in JS like you do in other languages). Also, this will not immediately execute function_reference unless you include (). I.e. function_reference is just that - a reference; passing in function_reference() would invoke the function immediately. Nov 24, 2015 at 0:04
39

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');
}
28

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>
5
  • 2
    The difficulty with this solution is that it actively uses a processor, which leads to increased power usage and a decrease in resources available for other threads/processes (e.g. other tabs, other programs). Sleep, by contrast, temporarily suspends a thread's use of system resources.
    – ramcdougal
    Jul 1, 2014 at 6:13
  • 1
    better to use Date.now() instead of new Date() and don't think about memory leaks
    – WayFarer
    Dec 4, 2014 at 12:26
  • 2
    Of course it is CPU intensive, but for quick and dirty testing it works
    – Maris B.
    Mar 25, 2015 at 9:21
  • 3
    A more compact routine: function delay(ms) { var start_time = Date.now(); while (Date.now() - start_time < ms); }
    – Duke
    Mar 18, 2016 at 6:46
  • ;(function(){function a(b,a){!0!==a&&(b*=1E3);for(var c=Date.now();Date.now()-c<b;);}window.hasOwnProperty("delay")||(window.delay=a)})(); Use secs or msecs. Example with 3 seconds: delay(3); Example with 500 milliseconds: delay(500, true);
    – SpYk3HH
    Jul 11, 2016 at 21:47
15

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!

2
  • 2
    Still it would be useful for testing purposes. Like delaying a form submission for a few seconds to evaluate page changes before a new HTTP request is made. Jan 2, 2013 at 19:15
  • 1
    @rushinge then set the callback to submit the form and disable the default form submit
    – Populus
    Jul 2, 2013 at 18:56
14

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

2
  • 2
    setInterval() should n't be use instead should use setTimeout
    – paul
    Jan 4, 2011 at 0:58
  • 9
    setTimeout() does it once, setInterval() does it repeatedly. If you want your code run every 5 seconds, setInterval() is made for the job.
    – rcoup
    Jun 8, 2011 at 2:26
11

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.

10

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

3
  • 2
    Well, it’s a busy loop that will drain the batteries of laptops and other mobile devices, and probably also prevent the UI from responding (or even displaying).
    – Ry-
    Dec 20, 2014 at 1:34
  • @U2744SNOWFLAKE Makes sense. Have updated the answer, for what I used this function for :) Dec 20, 2014 at 9:33
  • 2
    Works well enough in development for a quick & dirty (and temporary) solution. Apr 28, 2015 at 15:59
6

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');
});

0
5

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.

4

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.

3

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...
2

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());

1

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
1

The simplest solution to call your function with delay is:

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.