Javascript avoids multiple call

My problem here is that I want to avoid calling the javascript function for a period of time (say, 5 seconds) after calling it.

I created a link that calls the javascript function. If the user double-clicks, he is called twice, I want to avoid this.

Thanks Dewan

+4
source share
2 answers

I think the most reasonable way to handle this is to disable the link after clicking it, and then turn it back on when the function is launched. Assuming you have jQuery, something like ...

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

If you really need to wait a certain amount of time after calling the function, you can use setTimeout to reuse 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 comments below)

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

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

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

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

Such things are usually processed on the server, although client-side scripts are not particularly reliable - you cannot guarantee that the business will be implemented no matter what strategy you use.

+1
source

All Articles