Javascript sleep/delay/wait function

后端 未结 6 1200
时光取名叫无心
时光取名叫无心 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-03 23:51

    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.

提交回复
热议问题