Javascript sleep/delay/wait function Javascript sleep/delay/wait function javascript javascript

Javascript sleep/delay/wait function


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.


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