javascript - 我该如何延迟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();
});
});
解决方案
该
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
推荐阅读
- excel - EXCEL VBA:根据值范围格式化现有数字单元格
- python - Pandas Resample Upsample 最后日期/数据边缘
- visual-studio-code - 有没有办法像在 Sublime Text 中一样修改每种语言的默认注释标签
- git - 尝试变基以更正属性过滤器,但由于“未分级更改”而无法
- vba - 过滤/排序后阻止Excel跳到顶部
- php - Wordpress 将 php 和 html 模板转换为简码
- powerpoint - 更改布局时如何防止对象/文本改变颜色?
- javascript - 关于 Toggle with same Class Javascript No jQuery
- html -
HTML/CSS - 即使有标签也能保持元素在同一行 - discord - Discord.js Bot -- 如何检查每一天是哪一天