What is the most recommended/best way to stop multiple instances of a setTimeout function from being created (in javascript)?
An example (psuedo code):
function mouseClick() { moveDiv("div_0001", mouseX, mouseY); } function moveDiv(objID, destX, destY) { //some code that moves the div closer to destination ... ... ... setTimeout("moveDiv(objID, destX, destY)", 1000); ... ... ... }
My issue is that if the user clicks the mouse multiple times, I have multiple instances of moveDiv() getting called.
The option I have seen is to create a flag, that only allows the timeout to be called if no other instance is available...is that the best way to go?
I hope that makes it clear....
If you need to run a function multiple times, use the setInterval() method. To stop the timeout and prevent the function from executing, use the clearTimeout() method. The JavaScript setTimeout() method returns an ID which can be used in clearTimeout() method.
As specified in the HTML standard, browsers will enforce a minimum timeout of 4 milliseconds once a nested call to setTimeout has been scheduled 5 times.
The setTimeout() method executes a block of code after the specified time. The method executes the code only once. The commonly used syntax of JavaScript setTimeout is: setTimeout(function, milliseconds);
setTimeout(function, milliseconds); Its parameters are: function - a function containing a block of code. milliseconds - the time after which the function is executed.
when you call settimeout, it returns you a variable "handle" (a number, I think)
if you call settimeout a second time, you should first
clearTimeout( handle )
then:
handle = setTimeout( ... )
to help automate this, you might use a wrapper that associates timeout calls with a string (i.e. the div's id, or anything you want), so that if there's a previous settimeout with the same "string", it clears it for you automatically before setting it again,
You would use an array (i.e. dictionary/hashmap) to associate strings with handles.
var timeout_handles = [] function set_time_out( id, code, time ) /// wrapper { if( id in timeout_handles ) { clearTimeout( timeout_handles[id] ) } timeout_handles[id] = setTimeout( code, time ) }
There are of course other ways to do this ..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With