admin 管理员组

文章数量: 1086019

My problem here is i want to avoid calling a javascript function for a time period(say after 5 sec) after it has been called.

i created a link, which calls the javascript function.and if the user double clicks it is called twice i want to avoid that.

Thanks, Devan

My problem here is i want to avoid calling a javascript function for a time period(say after 5 sec) after it has been called.

i created a link, which calls the javascript function.and if the user double clicks it is called twice i want to avoid that.

Thanks, Devan

Share Improve this question asked May 3, 2011 at 6:07 DevanDevan 1701 gold badge6 silver badges15 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

I think the most sensible way to handle that is to disable the link once it is clicked, and then reenable it when the function is done running. Assuming you have jQuery available, something like...

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

If you really need to wait a set amount of time after the function is called, then you could use setTimeout to reenable the button.

$('#button').click(function () {
  $(this).attr("disabled", "true");
  doTheFunction();
  var btn = $(this);
  setTimeout(function () {
    btn.attr("disabled", "false");
  }, 5000);  // reenable the button 5 seconds later
});

EDIT: (for the ment below)

For a link, I would simulate the above by adding and removing a class, since you're right, there's no disabled attribute.

$('#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
});

Since you are using a link, not a button, and not jQuery (apparently), here's how to stop a function doing anything for 5 seconds (or whatever delay you want) after it has been called and done something:

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;
    }
  }
}());

This sort of thing is generally handled at the server though, since client scripts aren't particularly reliable - you can't guarantee that the dealy will be implemented, no matter what strategy you use.

本文标签: functionjavascript avoid multiple callStack Overflow