170

I can't get the .delay method working in jQuery:

$.delay(3000); // not working
$(queue).delay(3000); // not working

I'm using a while loop to wait until an uncontrolled changing value is greater than or equal to another and I can't find any way to hault execution for X seconds.

5
  • try using setTimeout in the callback Jan 17, 2012 at 14:31
  • what version of jquery are you using? Jan 17, 2012 at 14:31
  • 1
    that is not what the delay function is designed for, it is designed for use between queued jquery events (like fade().delay().show()). You need the setTimeOut function.
    – JoJa
    Jan 17, 2012 at 14:35
  • @JoJa: You are correct on the main point, however the no argument form of show (and hide) do not use the effects queue.
    – Jay Tomten
    Jan 17, 2012 at 14:40
  • 3
    Please, state what you are trying to achieve with the delay. All JavaScript executes on a single thread, and freezing it for X seconds may cause adverse user experience. Jan 17, 2012 at 14:41

10 Answers 10

277

You can also just delay some operation this way:

setTimeout(function (){
  
  // Something you want delayed.
            
}, 5000); // How long you want the delay to be, measured in milliseconds.
3
  • 10
    Just an FYI, this doesn't break the flow of execution, so if you need to "stop everything" for a few seconds, you're going to need something like what Niessner has posted. Jan 10, 2015 at 0:48
  • Yes... its a callback to the function and does not block. Thanks for the answer, it fixed my issue. May 2, 2015 at 20:46
  • if the frequency is extremely short and we expect this function to be running forever, will it eventually blow the stack? Sep 18, 2018 at 20:25
200

$.delay is used to delay animations in a queue, not halt execution.

Instead of using a while loop, you need to recursively call a method that performs the check every second using setTimeout:

var check = function(){
    if(condition){
        // run when condition is met
    }
    else {
        setTimeout(check, 1000); // check again in a second
    }
}

check();
6
  • 2
    I think, setTimeout is enough.
    – Jiemurat
    Oct 28, 2013 at 1:03
  • 3
    Your the bomb bro, this is exactly what I needed to fix my code.
    – jemiloii
    Feb 19, 2014 at 3:03
  • @Jiemurat and anyone else in the future: setTimeout doesn't break the flow of execution. The great code of Niessner obtain this untile the conditions became true!
    – Gabrer
    Dec 5, 2014 at 17:13
  • If you don't need to break the flow of execution, you can simply use setTimeout(). Jan 10, 2015 at 0:48
  • i always get "check is not a function", my check function has two parameters though
    – Black
    Mar 14, 2016 at 15:12
38

ES6 setTimeout

setTimeout(() => {
  console.log("we waited 204586560000 ms to run this code, oh boy wowwoowee!");
}, 204586560000);

Edit: 204586560000 ms is the approximate time between the original question and this answer... assuming I calculated correctly.

1
  • 8
    really nice using the approximate time from the original question to this answer
    – Fuzzybear
    Nov 30, 2018 at 17:13
21

If you are using ES6 features and you're in an async function, you can effectively halt the code execution for a certain time with this function:

const delay = millis => new Promise((resolve, reject) => {
  setTimeout(_ => resolve(), millis)
});

This is how you use it:

await delay(5000);

It will stall for the requested amount of milliseconds, but only if you're in an async function. Example below:

const myFunction = async function() {
  // first code block ...

  await delay(5000);

  // some more code, executed 5 seconds after the first code block finishes
}
2
  • 1
    I solved this problem a similar way in an async function by simply doing the following: await setTimeout(_ => {}, millis); then moving to the next line. Aug 17, 2020 at 16:56
  • 2
    await new Promise(resolve => setTimeout(resolve, 1000));
    – Splash
    Jun 29, 2022 at 15:13
10

jQuery's delay function is meant to be used with effects and effect queues, see the delay docs and the example therein:

$('#foo').slideUp(300).delay(800).fadeIn(400);

If you want to observe a variable for changes, you could do something like

(function() {
    var observerInterval = setInterval(function() {
        if (/* check for changes here */) {
           clearInterval(observerInterval);
           // do something here
        }
    }, 1000);
})();
3
  • setInterval has a second mandatory parameter, the time in milliseconds ;) Oct 12, 2015 at 7:26
  • 1
    Thanks @sara.potyscki, fixed.
    – Julian D.
    Oct 12, 2015 at 9:11
  • @JulianD. Thank you for this suggestion. I landed on this question while googling for a solution. This is exactly what I needed for my project. Sep 22, 2017 at 14:57
9

JavaScript setTimeout is a very good solution:

function funcx()
   {
   // your code here
   // break out here if needed
   setTimeout(funcx, 3000);
   }

funcx();

The delay function in jQuery is mostly used for delaying animations in a jQuery animation queue.

7

delay() doesn't halt the flow of code then re-run it. There's no practical way to do that in JavaScript. Everything has to be done with functions which take callbacks such as setTimeout which others have mentioned.

The purpose of jQuery's delay() is to make an animation queue wait before executing. So for example $(element).delay(3000).fadeIn(250); will make the element fade in after 3 seconds.

5
    function sleep(num) {
        let now = new Date();
        let stop = now.getTime() + num;
        while(true) {
            now = new Date();
            if(now.getTime() > stop) return;
        }
    }

    sleep(1000);   // 1 second 
    alert('here');

It gets the current time in milliseconds, adds num (which is a future time) where you've adding num many milliseconds to the current time.

An infinite while loop starts up checking the current time until the current time is later than the time we specified in the previous paragraph, once that has occurred the function stops running and execution continues to what ever is after this function call.

2
  • Please provide some information about the answer so that future readers get more information from your answer.
    – Not A Bot
    Feb 24, 2021 at 12:24
  • 1
    this approach uses CPU extremely hard, such sleep might cause the freeze of the webpage and users will not like it. Don't use it.
    – walv
    Mar 25, 2022 at 14:38
5

Javascript is an asynchronous programming language so you can't stop the execution for a of time; the only way you can [pseudo]stop an execution is using setTimeout() that is not a delay but a "delayed function callback".

1
4

Only javascript It will work without jQuery

<!DOCTYPE html>
<html>
    <head>
        <script>
            function sleep(miliseconds) {
                var currentTime = new Date().getTime();
                while (currentTime + miliseconds >= new Date().getTime()) {
                }
            }

            function hello() {
                sleep(5000);
                alert('Hello');
            }
            function hi() {
                sleep(10000);
                alert('Hi');
            }
        </script>
    </head>
    <body>
        <a href="#" onclick="hello();">Say me hello after 5 seconds </a>
        <br>
        <a href="#" onclick="hi();">Say me hi after 10 seconds </a>


    </body>
</html>
1
  • 2
    Looping to wait in javascript is a bad idea! All javascript functionality will stop while the loop is running. This will have unanticipated side-effects. It's much better to use non-blocking functions like setTimeout().
    – Kevin G.
    Jul 12, 2016 at 20:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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