我的问题是,我想在调用 JavaScript 函数后避免一段时间(比如 5 秒)再次调用它。
我创建了一个链接来调用 JavaScript 函数。如果用户双击它,函数会被调用两次,我想避免这种情况发生。
谢谢, Devan
我创建了一个链接来调用 JavaScript 函数。如果用户双击它,函数会被调用两次,我想避免这种情况发生。
谢谢, Devan
我认为处理这个问题最明智的方式是在链接被点击后禁用它,然后在函数运行完成后重新启用它。假设您可使用jQuery,可以使用以下代码:
$('#button').click(function () {
$(this).attr("disabled", "true");
doTheFunction();
$(this).attr("disabled", "false");
});
$('#button').click(function () {
$(this).attr("disabled", "true");
doTheFunction();
var btn = $(this);
setTimeout(function () {
btn.attr("disabled", "false");
}, 5000); // reenable the button 5 seconds later
});
编辑:(针对下面的评论)
对于一个链接,我会通过添加和删除类来模拟上述情况,因为您说得对,没有禁用属性。
$('#link').click(function () {
if ($(this).hasClass('disabled_link')) {
return;
}
$(this).addClass("disabled_link");
doTheFunction();
var link = $(this);
setTimeout(function () {
link.removeClass("disabled_link");
}, 5000); // reenable the button 5 seconds later
});
如果您正在使用链接而不是按钮,并且没有使用jQuery(显然),那么以下是在函数被调用并完成某些操作后停止函数执行5秒钟(或任何延迟)的方法:
var someFn = (function() {
var lastCalled;
return function() {
var now = new Date();
var limit = 5000; // minimum milliseconds between calls
if (!lastCalled || (now - lastCalled) > limit) {
lastCalled = now;
// do stuff
alert('hey');
} else {
return;
}
}
}());
这种事情通常在服务器上处理,因为客户端脚本并不是特别可靠 - 无论你使用什么策略,都不能保证延迟将会被实现。