29

Sorry if this question has already been asked here before, I could not find a suitable answer.

I am wanting to create a JavaScript sleep/delay/wait function that I can call anywhere in the script, like jQuery's .delay()

I am not able to use setTimeout, as I have a script that is generated by php, and so am not able to put it into two different functions, with the timeout in the middle. I need to create a function that allows me to do

alert("time started");
sleep(4000);
alert("time up");

I really do not want to use jQuery.

10
  • 1
    No, you can't do it like that. As simple as that. Use setTimeout or similar solutions. Commented Oct 15, 2013 at 19:15
  • 1
    possible duplicate of What do I do if I want a JavaScript version of sleep()? Commented Oct 15, 2013 at 19:17
  • There are many identical questions. You found no suitable answer because you didn't accept that JavaScript doesn't work like it works. Commented Oct 15, 2013 at 19:18
  • 1
    setTimeout, whether you like it or not, is the right answer. You need to restructure your page or functions to handle it if you need delays. Commented Oct 15, 2013 at 19:20
  • 1
    @user2704237 This reads like you are trying to implement a new higher language which is based upon JavaScript. You can't implement something fundamentally counter to how JavaScript works if it is based on it.
    – Paul S.
    Commented Oct 15, 2013 at 19:28

6 Answers 6

25

Here's a solution using the new async/await syntax.

async function testWait() {
    alert('going to wait for 5 second');
    await wait(5000);
    alert('finally wait is over');
}

function wait(time) {
    return new Promise(resolve => {
        setTimeout(resolve, time);
    });
}

Note: You can call function wait only in async functions

1
  • 1
    Instead of creating a function that calls resolve(), you can just replace it with the resolve function itself: replace () => { resolve(); } with resolve Commented Jan 4, 2022 at 0:48
19

You cannot just put in a function to pause Javascript unfortunately.

You have to use setTimeout()

Example:

function startTimer () {
    timer.start();
    setTimeout(stopTimer,5000);
}

function stopTimer () {
    timer.stop();
}

EDIT:

For your user generated countdown, it is just as simple.

HTML:

<input type="number" id="delay" min="1" max="5">

JS:

var delayInSeconds = parseInt(delay.value);
var delayInMilliseconds = delayInSeconds*1000;

function startTimer () {
    timer.start();
    setTimeout(stopTimer,delayInMilliseconds);
}

function stopTimer () {
    timer.stop;
}

Now you simply need to add a trigger for startTimer(), such as onchange.

3
  • and what is 'timer' supposed to be? I get an Uncaught ReferenceError: timer is not defined
    – gicalle
    Commented Feb 11, 2015 at 9:54
  • timer.start() and timer.stop() are placeholder functions. Replace them with whatever commands you want
    – Deep
    Commented Feb 11, 2015 at 11:12
  • Now you can, in ES2015 + async/await. Commented Oct 7, 2016 at 10:12
10

You will have to use a setTimeout so I see your issue as

I have a script that is generated by PHP, and so am not able to put it into two different functions

What prevents you from generating two functions in your script?

function fizz() {
    var a;
    a = 'buzz';
    // sleep x desired
    a = 'complete';
}

Could be rewritten as

function foo() {
    var a; // variable raised so shared across functions below
    function bar() { // consider this to be start of fizz
        a = 'buzz';
        setTimeout(baz, x); // start wait
    } // code split here for timeout break
    function baz() { // after wait
        a = 'complete';
    } // end of fizz
    bar(); // start it
}

You'll notice that a inside baz starts as buzz when it is invoked and at the end of invocation, a inside foo will be "complete".

Basically, wrap everything in a function, move all variables up into that wrapping function such that the contained functions inherit them. Then, every time you encounter wait NUMBER seconds you echo a setTimeout, end the function and start a new function to pick up where you left off.

0
2

The behavior exact to the one specified by you is impossible in JS as implemented in current browsers. Sorry.

Well, you could in theory make a function with a loop where loop's end condition would be based on time, but this would hog your CPU, make browser unresponsive and would be extremely poor design. I refuse to even write an example for this ;)


Update: My answer got -1'd (unfairly), but I guess I could mention that in ES6 (which is not implemented in browsers yet, nor is it enabled in Node.js by default), it will be possible to write a asynchronous code in a synchronous fashion. You would need promises and generators for that.

You can use it today, for instance in Node.js with harmony flags, using Q.spawn(), see this blog post for example (last example there).

2
  • Yeah, I wonder why my answer got -1'd. I'd love to see the code as written by OP to work in ES5 browsers. When you show it, please -1 me as much as you want.
    – kamituel
    Commented Jul 21, 2014 at 7:13
  • This is the correct idea. Since this question is a dupe, I left an answer based on ES6 on the original question. Commented Oct 7, 2016 at 10:13
0

You could use the following code, it does a recursive call into the function in order to properly wait for the desired time.

function exportar(page,miliseconds,totalpages)
{
    if (page <= totalpages)
    {
        nextpage = page + 1;
        console.log('fnExcelReport('+ page +'); nextpage = '+ nextpage + '; miliseconds = '+ miliseconds + '; totalpages = '+ totalpages );
        fnExcelReport(page);
        setTimeout(function(){
            exportar(nextpage,miliseconds,totalpages);
        },miliseconds);
    };
}
0
-1

You can use this -

function sleep(milliseconds) {
    var start = new Date().getTime();
    for (var i = 0; i < 1e7; i++) {
        if ((new Date().getTime() - start) > milliseconds){
            break;
        }
    }
}
4
  • call this function where you want to give delay, like sleep(1000);
    – Tushar
    Commented Feb 13, 2015 at 5:20
  • 3
    A spin-wait? Ouch. That's going to hurt mobile devices. Commented Feb 13, 2015 at 5:45
  • 1
    This doesn't work since the condition of the for loop can be met quite quickly. Even if you remove the condition of the for loop (e.g. for(;;){...}) you'll end up boggling the single thread and therefore the DOM.
    – Auxiliary
    Commented Apr 13, 2017 at 0:50
  • 1
    that caused my chrome browser to lock up and consume excess resources. Not good. Commented Sep 28, 2018 at 0:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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