首页 > 解决方案 > 我该如何延迟javascript执行?

问题描述

我有一些 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();
    });     

});    

标签: javascriptjquery

解决方案


使用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


推荐阅读