Javascript sleep/delay/wait function

后端 未结 6 1201
时光取名叫无心
时光取名叫无心 2021-01-03 23:13

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 c

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-04 00:13

    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:

    
    

    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.

提交回复
热议问题