[javascript] Javascript sleep/delay/wait function

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.

This question is related to javascript function delay sleep wait

The answer is


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

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


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


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

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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to function

$http.get(...).success is not a function Function to calculate R2 (R-squared) in R How to Call a Function inside a Render in React/Jsx How does Python return multiple values from a function? Default optional parameter in Swift function How to have multiple conditions for one if statement in python Uncaught TypeError: .indexOf is not a function Proper use of const for defining functions in JavaScript Run php function on button click includes() not working in all browsers

Examples related to delay

Delaying function in swift How to create a delay in Swift? How to make java delay for a few seconds? Proper way to wait for one function to finish before continuing? Javascript sleep/delay/wait function How can I perform a short delay in C# without using sleep? How to create javascript delay function JavaScript sleep/wait before continuing Adding delay between execution of two following lines How to put a delay on AngularJS instant search?

Examples related to sleep

How to make the script wait/sleep in a simple way in unity How do I make a delay in Java? How to create a sleep/delay in nodejs that is Blocking? Javascript sleep/delay/wait function How can I perform a short delay in C# without using sleep? How to add a "sleep" or "wait" to my Lua Script? How to create javascript delay function JavaScript sleep/wait before continuing powershell mouse move does not prevent idle mode What is the proper #include for the function 'sleep()'?

Examples related to wait

How to make the script wait/sleep in a simple way in unity How do I make a delay in Java? Wait some seconds without blocking UI execution Protractor : How to wait for page complete after click a button? How to wait until an element is present in Selenium? Javascript sleep/delay/wait function How to wait till the response comes from the $http request, in angularjs? How to add a "sleep" or "wait" to my Lua Script? Concept behind putting wait(),notify() methods in Object class How can I wait for 10 second without locking application UI in android