Javascript sleep/delay/wait function

user2704237 picture user2704237 · Oct 15, 2013 · Viewed 196.3k times · Source

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.

Answer

Deep picture Deep · Oct 15, 2013

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.