只需设置一个超时:
var tim;//global, I'll provide a (more complex) solution that doesn't need them, too
function loadPopupBox() { // to load the Popupbox
$('#popup_box').fadeIn("slow");
tim = setTimeout(function()
{
$('#popup_box').click();
},30000);
}
$('#popupBoxAccept').click( function() {
clearTimeout(tim);
});
现在,不使用EVIL全局变量:
$(document).ready(function()
{
(function(popup,accept,decline)
{
popup.fadeIn("slow");
var tim = setTimeout(function()
{
accept.click();//<-- access to reference is preserved
},30000);
accept.click(function()
{
clearTimeout(tim);
//do accept stuff
});
decline.click(function()
{
clearTimeout(tim);//<-- need that here, too!
//do decline stuff
});
})($('#popup_box'),$('#popupBoxAccept'),$('#popupBoxDecline'));
//pass all 3 elements as argument --> less typing, and is more efficient:
//the DOM is only searched once for each element
});
为什么这很有用?很简单:您现在可以var tim
在另一个上下文中使用,而不会丢失对超时的引用。闭包,名字就说明了一切:所有变量和引用都整齐地捆绑在同一个范围内,并且不能访问,只能在声明的范围内访问:
var foo = (function()
{
var invisible = 'Now you see me';
return function()
{
return invisible;
}
};
console.log(invisible);//<-- undefined
var invisible = 'Now you don\'t';
console.log(foo());//<-- Now you see me
console.log(invisible);//Now you don\'t