Search code examples
javascriptfunctiondelaysleepwait

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.


Solution

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