PDA

View Full Version : settimeout used to trigger cleartimeout won't work to stop infinite loop



mr_fitz
Jan 26th, 2007, 09:38 PM
I would like to stop an infinitely looping function that "spins" the color attributes of tables cells and is supposed to stop once a cell has been picked. Everything works fine, except I cannot stop the infinite loop that spins the cell attribute changer. In the second code section below are two functions, the one that rotates the cells and the one to stop the infinite loop.
I try to call the StopRotate with a settimeout as follows:


startpick = setTimeout(function() {
document.getElementById(pick).setAttribute('className','dmmlgreen');
StopRotate();
},5000);

but the RotateCell function keeps rotating. If I use a button to call StopRotate, it does indeed stop RotateCell. Thus how do I call StopRotate to happen after a specified amount of time? Thanks.


function StopRotate(){
clearTimeout(startrotate);
}

function RotateCell(newcell) {
//alert(startrotate);
//cycle through id_array and highlight the cells with a settimeout like a roulette wheel
//at the end of the timeout period in SelectCell un-setAttribute the last cell to its default attribute.

mixcell=newcell;
var lastone = document.nosend.lasthighlight.value;
var howlong = old_array.length - 1;
//var highlight=old_array[mixcell];
var highlight=old_array[mixcell];

//alert(mixcell,highlight);

if (lastone!=1986){
document.getElementById(lastone).setAttribute('className','dmml');
}
document.getElementById(highlight).setAttribute('className','dmmlbig');
document.nosend.lasthighlight.value=highlight;

if (mixcell==howlong){
mixcell=0;
}else{
mixcell++;
}

document.getElementById('message2').innerHTML='highlight:'+highlight+' mixcell:'+mixcell+' lastone:'+lastone;

//startrotate=setTimeout(function() {
//RotateCell(mixcell);
// },1000);
startrotate = setTimeout("RotateCell(mixcell)", 1000);
}//end function

david_kw
Jan 26th, 2007, 10:27 PM
It looks ok at first glance to me. I'd start by commenting out this line.



startpick = setTimeout(function() {
// document.getElementById(pick).setAttribute('className','dmmlgreen');
StopRotate();
},5000);


and see if it stops after 5 seconds. The code fragment you gave didn't say how pick was defined, so maybe that line is causing an error which stop StopRotate() from being called. If you post a link to the page we might be able to find other possibilities that it doesn't work.

david_kw

mr_fitz
Jan 28th, 2007, 10:05 PM
Well it turns out the problem is that the 1second loop fires at exactly the same time the 5 second cleartimeout tries to stop it. Change to 0.95 second and all is good (i.e so the smaller one is not evenly divisible into the larger):D !

david_kw
Jan 28th, 2007, 10:33 PM
Ahh fun stuff. :) That'll be a good thing to keep in mind when I do future timer work.

david_kw