Stoping a javascript function.

new2AMD

Diamond Member
Jul 18, 2001
5,312
0
0
I have a start button calling a function. I want a stop button to stop that same function. Is there something like unload or onclick that will stop the function that is running?
 

hellman69

Member
Feb 15, 2003
180
0
71
Without seeing what you are trying to do, I'll throw a thought out there. Declare a global variable (blRun) set to true.

For the Stop button, have an onClick action that sets blRun = false;

For the Start function, simply add checks for blRun. If it's false, then return. If true, keep going.

Trevor
 

MrChad

Lifer
Aug 22, 2001
13,507
3
81
Originally posted by: hellman69
Without seeing what you are trying to do, I'll throw a thought out there. Declare a global variable (blRun) set to true.

For the Stop button, have an onClick action that sets blRun = false;

For the Start function, simply add checks for blRun. If it's false, then return. If true, keep going.

Trevor

This will work, but make sure you use setTimeout() to loop your function, or you'll likely lock up the browser. Something like:

var bRun = false;

function myFunction(){
....if (bRun){
........// do some stuff
........setTimeout('myFunction()',1000);
....}
}

function startFunction(){
....bRun = true;
....setTimeout('myFunction()',1000);
}

function stopFunction(){
....bRun = false;
}