Timeout and for-loops

Jack Michaelson's picture

He has: 1,733 posts

Joined: Dec 1999

Hi,

I have a for loop that calls a setTimeout like this:

for(j=0; j < 100; j++)
{
  To_ID = setTimeout("MyFunction", 3000);
}
'

When I call the clearTimeout-function like this:

clearTimeout(To_ID);
'
the function MyFunction keeps on executing, which makes sense as it is called more than once. Actually, it executes (remaining j - 1) times.
It seems that there are more instances of To_ID made in that for-loop and I want to clear them all.
But... and you all saw this one coming... how?

Anyone have an idea on the direction I should go? Is To_ID an array item? If yes, what array?

Thanx a lot.

Shakespeare: onclick || !(onclick)

Jack Michaelson's picture

He has: 1,733 posts

Joined: Dec 1999

Nevermind Smiling
Solved it like this:
Now I set the timeOuts in an array:

for(j=0; j < (100); j++)
{
ToArr.length = ToArr.length + 1;
  ToArr[ToArr.length - 1] = setTimeout("MyFunction", 3000);
}
'

and clear them like this:

for(a=0; a<ToArr.length; a++)
{
clearTimeout(ToArr[a]);
}
'

Shakespeare: onclick || !(onclick)

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.