Execute script after specific delay using JavaScript

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

    As other said, setTimeout is your safest bet
    But sometimes you cannot separate the logic to a new function then you can use Date.now() to get milliseconds and do the delay yourself....

    function delay(milisecondDelay) {
       milisecondDelay += Date.now();
       while(Date.now() < milisecondDelay){}
    }
    
    alert('Ill be back in 5 sec after you click OK....');
    delay(5000);
    alert('# Im back # date:' +new Date());

提交回复
热议问题