Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you handle multiple instances of setTimeout()?

Tags:

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....

like image 477
Markus Avatar asked Nov 24 '08 18:11

Markus


People also ask

How do I set setTimeout multiple times?

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.

How many times setTimeout executed?

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.

What is the use of setTimeout () in JavaScript?

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

Which are the parameters of setTimeout () function?

setTimeout(function, milliseconds); Its parameters are: function - a function containing a block of code. milliseconds - the time after which the function is executed.


1 Answers

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 ..

like image 84
hasen Avatar answered Sep 18 '22 18:09

hasen