Execute script after specific delay using JavaScript

前端 未结 15 2128
陌清茗
陌清茗 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: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

提交回复
热议问题