Execute script after specific delay using JavaScript

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

    I really liked Maurius' explanation (highest upvoted response) with the three different methods for calling setTimeout.

    In my code I want to automatically auto-navigate to the previous page upon completion of an AJAX save event. The completion of the save event has a slight animation in the CSS indicating the save was successful.

    In my code I found a difference between the first two examples:

    setTimeout(window.history.back(), 3000);
    

    This one does not wait for the timeout--the back() is called almost immediately no matter what number I put in for the delay.

    However, changing this to:

    setTimeout(function() {window.history.back()}, 3000);
    

    This does exactly what I was hoping.

    This is not specific to the back() operation, the same happens with alert(). Basically with the alert() used in the first case, the delay time is ignored. When I dismiss the popup the animation for the CSS continues.

    Thus, I would recommend the second or third method he describes even if you are using built in functions and not using arguments.

提交回复
热议问题