JavaScript避免多次调用

4
我的问题是,我想在调用 JavaScript 函数后避免一段时间(比如 5 秒)再次调用它。
我创建了一个链接来调用 JavaScript 函数。如果用户双击它,函数会被调用两次,我想避免这种情况发生。
谢谢, Devan
2个回答

5

我认为处理这个问题最明智的方式是在链接被点击后禁用它,然后在函数运行完成后重新启用它。假设您可使用jQuery,可以使用以下代码:

$('#button').click(function () {
  $(this).attr("disabled", "true");
  doTheFunction();
  $(this).attr("disabled", "false");
});

如果您确实需要在函数调用后等待一定的时间,那么您可以使用setTimeout来重新启用按钮。
$('#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
});

1
我正在使用<a></a>标签来调用函数。我认为<a>标签没有禁用属性。如果我错了,请纠正我。 - Devan

4

如果您正在使用链接而不是按钮,并且没有使用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;
    }
  }
}());

这种事情通常在服务器上处理,因为客户端脚本并不是特别可靠 - 无论你使用什么策略,都不能保证延迟将会被实现。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接