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

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() {

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(){

function RotateCell(newcell) {
//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.

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


if (lastone!=1986){

if (mixcell==howlong){

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

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

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

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.


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 !

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.