Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript avoid multiple call

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

like image 580
Devan Avatar asked Feb 24 '23 08:02

Devan


2 Answers

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
});
like image 183
goggin13 Avatar answered Feb 26 '23 20:02

goggin13


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.

like image 23
RobG Avatar answered Feb 26 '23 21:02

RobG