javascript避免多次通话

Dev*_*van 4 javascript function

我的问题是我想避免在调用后调用javascript函数一段时间(比如5秒后).

我创建了一个链接,它调用了javascript函数.如果用户双击它,则调用两次我想避免这种情况.

谢谢,德万

gog*_*n13 5

我认为最合理的处理方法是在单击链接后禁用链接,然后在函数运行完成后重新启用它.假设你有jQuery可用,像...

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

如果在调用函数后确实需要等待一段时间,则可以使用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
});
Run Code Online (Sandbox Code Playgroud)

编辑:(以下评论)

对于链接,我会通过添加和删除类来模拟上面的内容,因为你是对的,没有禁用的属性.

$('#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
});
Run Code Online (Sandbox Code Playgroud)