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….
when you call settimeout, it returns you a variable ‘handle’ (a number, I think)
if you call settimeout a second time, you should first
then:
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.
There are of course other ways to do this ..