4

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

2 Answers 2

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 comment 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
});
Sign up to request clarification or add additional context in comments.

1 Comment

i am using a <a></a> tag for calling the function. and i think <a> tag has no disable attribute. Correct me if i'm wrong.
4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.