Execute script after specific delay using JavaScript

前端 未结 15 1763
陌清茗
陌清茗 2020-11-22 12:29

Is there any JavaScript method similar to the jQuery delay() or wait() (to delay the execution of a script for a specific amount of time)?

相关标签:
15条回答
  • 2020-11-22 12:49

    You can also use window.setInterval() to run some code repeatedly at a regular interval.

    0 讨论(0)
  • 2020-11-22 12:51

    why can't you put the code behind a promise? (typed in off the top of my head)

    new Promise(function(resolve, reject) {
      setTimeout(resolve, 2000);
    }).then(function() {
      console.log('do whatever you wanted to hold off on');
    });

    0 讨论(0)
  • 2020-11-22 12:52

    If you really want to have a blocking (synchronous) delay function (for whatsoever), why not do something like this:

    <script type="text/javascript">
        function delay(ms) {
            var cur_d = new Date();
            var cur_ticks = cur_d.getTime();
            var ms_passed = 0;
            while(ms_passed < ms) {
                var d = new Date();  // Possible memory leak?
                var ticks = d.getTime();
                ms_passed = ticks - cur_ticks;
                // d = null;  // Prevent memory leak?
            }
        }
    
        alert("2 sec delay")
        delay(2000);
        alert("done ... 500 ms delay")
        delay(500);
        alert("done");
    </script>
    
    0 讨论(0)
  • 2020-11-22 12:52

    If you only need to test a delay you can use this:

    function delay(ms) {
       ms += new Date().getTime();
       while (new Date() < ms){}
    }
    

    And then if you want to delay for 2 second you do:

    delay(2000);
    

    Might not be the best for production though. More on that in the comments

    0 讨论(0)
  • 2020-11-22 12:53

    The simplest solution to call your function with delay is:

    function executeWithDelay(anotherFunction) {
        setTimeout(anotherFunction, delayInMilliseconds);
    }
    
    0 讨论(0)
  • 2020-11-22 12:59

    The simple reply is:

    setTimeout(
        function () {
            x = 1;
        }, 1000);
    

    The function above waits for 1 second (1000 ms) then sets x to 1. Obviously this is an example; you can do anything you want inside the anonymous function.

    0 讨论(0)
提交回复
热议问题