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

nyedidikeke
  • 6,899
  • 7
  • 44
  • 59
Niyaz
  • 53,943
  • 55
  • 151
  • 182

15 Answers15

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

Alexander Elgin
  • 6,796
  • 4
  • 40
  • 50
Marius
  • 57,995
  • 32
  • 132
  • 151
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.

kenorb
  • 155,785
  • 88
  • 678
  • 743
Abhinav
  • 2,876
  • 3
  • 22
  • 22
  • 3
    It's not a expression that is executed it's a function. @Marius' answer illustrates that. – pedrofurla Oct 27 '12 at 03:45
  • 123
    this is not a delay, it's a fork. Delay should work in same thread. – DragonLord Oct 31 '12 at 20:09
  • 14
    This will immediately execute function_reference. To "work" (asynchronously) it should be stated as: setTimeout(function () { MethodToCall(); }, 1000); – Youp Bernoulli Nov 17 '14 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. – Danny Bullis Nov 24 '15 at 00: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');
}
Alexander Elgin
  • 6,796
  • 4
  • 40
  • 50
Polsonby
  • 22,825
  • 19
  • 59
  • 74
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>
Mario Werner
  • 1,771
  • 14
  • 24
  • 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 01 '14 at 06:13
  • 1
    better to use Date.now() instead of new Date() and don't think about memory leaks – WayFarer Dec 04 '14 at 12:26
  • 2
    Of course it is CPU intensive, but for quick and dirty testing it works – Maris B. Mar 25 '15 at 09:21
  • 3
    A more compact routine: function delay(ms) { var start_time = Date.now(); while (Date.now() - start_time < ms); } – Duke Mar 18 '16 at 06:46
  • `;(function(){function a(b,a){!0!==a&&(b*=1E3);for(var c=Date.now();Date.now()-c – SpYk3HH Jul 11 '16 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!

Patrick
  • 90,362
  • 11
  • 51
  • 61
  • 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. – NightWatchman Jan 02 '13 at 19:15
  • 1
    @rushinge then set the callback to submit the form and disable the default form submit – Populus Jul 02 '13 at 18:56
14

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

rcoup
  • 5,372
  • 2
  • 32
  • 36
  • 2
    setInterval() should n't be use instead should use setTimeout – paul Jan 04 '11 at 00: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 08 '11 at 02: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.

mttrb
  • 8,297
  • 3
  • 35
  • 57
narasi
  • 463
  • 3
  • 8
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

Christoffer
  • 7,436
  • 4
  • 40
  • 42
  • 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 '14 at 01:34
  • @U2744SNOWFLAKE Makes sense. Have updated the answer, for what I used this function for :) – Christoffer Dec 20 '14 at 09:33
  • 2
    Works well enough in development for a quick & dirty (and temporary) solution. – HumanInDisguise Apr 28 '15 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');
});
Al Joslin
  • 765
  • 10
  • 14
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.

Luca
  • 968
  • 1
  • 9
  • 17
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.

Alexander Elgin
  • 6,796
  • 4
  • 40
  • 50
Doug
  • 235
  • 4
  • 11
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...
Zuhair Taha
  • 2,808
  • 2
  • 35
  • 33
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());
JavaSheriff
  • 7,074
  • 20
  • 89
  • 159
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
JohnnyIV
  • 109
  • 5
1

The simplest solution to call your function with delay is:

function executeWithDelay(anotherFunction) {
    setTimeout(anotherFunction, delayInMilliseconds);
}
Jackkobec
  • 5,889
  • 34
  • 34