簡體   English   中英

我如何去延遲 javascript 執行?

[英]How do I go about delaying javascript execution?

我有一些 javascript 代碼,它在加載網頁時顯示一個表單。 我需要在訪問者訪問網站 2 分鍾后執行代碼。 我該怎么做? 下面是我的代碼:

setTimeout(function(){document.getElementById("dialog").innerHTML="";}, 120000);

$(document).ready(function() {  

        var id = '#dialog';

        //Get the screen height and width
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();

        //Set heigth and width to mask to fill up the whole screen
        $('#mask').css({'width':maskWidth,'height':maskHeight});

        //transition effect     
        $('#mask').fadeIn(500); 
        $('#mask').fadeTo("slow",0.9);  

        //Get the window height and width
        var winH = $(window).height();
        var winW = $(window).width();

        //Set the popup window to center
        $(id).css('top',  winH/2-$(id).height()/2);
        $(id).css('left', winW/2-$(id).width()/2);

        //transition effect
        $(id).fadeIn(2000);     

    //if close button is clicked
    $('.window .close').click(function (e) {
        //Cancel the link behavior
        e.preventDefault();

        $('#mask').hide();
        $('.window').hide();
    });     

    //if mask is clicked
    $('#mask').click(function () {
        $(this).hide();
        $('.window').hide();
    });     

});    

使用window.setTimeout()

setTimeout()方法 [...] 設置一個計時器,一旦計時器到期,它就會執行一個函數或指定的一段代碼。

句法

var timeoutID = scope.setTimeout(function[, delay, arg1, arg2, ...]); var timeoutID = scope.setTimeout(function[, delay]); var timeoutID = scope.setTimeout(code[, delay]);

所以在你的情況下,你可以這樣做:

// When the page first loads...
$(document).ready(function() {
  // ...wait for two minutes...
  window.setTimeout(function() {
    // ...and then run this code.
  }, 120000)
})

更多詳情: https : //developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout

代碼必須在setTimeout()內部,而不是外部。 嘗試一下...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM