By Niyaz


2008-08-24 05:10:57 8 Comments

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

13 comments

@user648026 2018-07-20 21:58:45

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 ' +new Date());

@Doug 2017-11-09 23:59:02

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.

@Marius 2008-08-24 10:01:16

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

@Vinayak Garg 2012-07-09 05:52:33

+1 this answer includes important details, that other missed.

@Polsonby 2008-08-24 08:53:14

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

@Abhinav 2008-08-24 05:18:18

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.

@pedrofurla 2012-10-27 03:45:36

It's not a expression that is executed it's a function. @Marius' answer illustrates that.

@DragonLord 2012-10-31 20:09:02

this is not a delay, it's a fork. Delay should work in same thread.

@Nerve 2013-04-24 07:42:47

Delay should work synchronously. This is asynchronous.

@Bernoulli IT 2014-11-17 19:39:54

This will immediately execute function_reference. To "work" (asynchronously) it should be stated as: setTimeout(function () { MethodToCall(); }, 1000);

@Danny Bullis 2015-11-24 00:04:12

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.

@Luca 2017-01-21 23:08:57

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.

@Al Joslin 2017-01-15 23:36:20

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

@Luca 2017-01-21 23:06:12

This works, but it's more complicated than necessary.

@Patrick 2008-08-24 05:14:30

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!

@rushinge 2013-01-02 19:15:53

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.

@Populus 2013-07-02 18:56:23

@rushinge then set the callback to submit the form and disable the default form submit

@Emmet Arries 2016-03-22 01:47:45

Bad idea to leave a link as the code...as now it doesn't work.

@Patrick 2016-03-22 22:29:35

Or you know, I could just fix it.

@JohnnyIV 2016-02-05 18:17:22

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

@Christoffer 2014-12-20 01:13:19

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

@Ry- 2014-12-20 01:16:11

This is not a good idea.

@Christoffer 2014-12-20 01:30:25

@U2744 SNOWFLAKE Can you try and be a bit more precise in your comment

@Ry- 2014-12-20 01:34:50

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

@Christoffer 2014-12-20 09:33:06

@U2744SNOWFLAKE Makes sense. Have updated the answer, for what I used this function for :)

@HumanInDisguise 2015-04-28 15:59:35

Works well enough in development for a quick & dirty (and temporary) solution.

@Mario Werner 2014-06-30 11:03:20

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>

@ramcdougal 2014-07-01 06:13:27

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.

@WayFarer 2014-12-04 12:26:48

better to use Date.now() instead of new Date() and don't think about memory leaks

@Maris B. 2015-03-25 09:21:31

Of course it is CPU intensive, but for quick and dirty testing it works

@Gui Imamura 2015-05-06 23:11:56

I want a version of it that doesn't lock the thread, so I can refresh the DOM before delaying (to answer to this question). Is there any way to do so?

@Duke 2016-03-18 06:46:42

A more compact routine: function delay(ms) { var start_time = Date.now(); while (Date.now() - start_time < ms); }

@SpYk3HH 2016-07-11 21:47:11

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

@narasi 2012-01-09 02:52:18

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.

@rcoup 2008-08-24 05:29:51

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

@paul 2011-01-04 00:58:18

setInterval() should n't be use instead should use setTimeout

@rcoup 2011-06-08 02:26:03

setTimeout() does it once, setInterval() does it repeatedly. If you want your code run every 5 seconds, setInterval() is made for the job.

Related Questions

Sponsored Content

88 Answered Questions

[SOLVED] How do JavaScript closures work?

58 Answered Questions

[SOLVED] How can I merge properties of two JavaScript objects dynamically?

69 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5207650 View
  • 6505 Score
  • 69 Answer
  • Tags:   javascript arrays

25 Answered Questions

69 Answered Questions

[SOLVED] What is the JavaScript version of sleep()?

  • 2009-06-04 14:41:10
  • fmsf
  • 1949195 View
  • 1652 Score
  • 69 Answer
  • Tags:   javascript sleep

11 Answered Questions

[SOLVED] How to insert an item into an array at a specific index?

12 Answered Questions

36 Answered Questions

[SOLVED] How do you get a timestamp in JavaScript?

48 Answered Questions

Sponsored Content