Stop looping in a function from another function in JavaScript

I want to stop the loop in a function from another function in JavaScript. Here is the code I tried:

<a onmousedown="startLoop();" onmouseup="stopLoop();" >
   Start loop
</a>

<script>
var static loop = 1;

function startLoop() {
    while(loop ==1) {
    }
    alert("stop"); //This line is not executed
}

function stopLoop() {
    loop = 2;
}
</script>

Here is the fiddle: http://jsfiddle.net/A5h8k/4/

+5
source share
1 answer

This one is var static loop = 1;not valid, var loop = 1;but you are starting an endless cycle, so you cannot stop it this way.

Use setInterval instead

var int = self.setInterval(function(){myLoop()},100);
function myLoop() {
    //do stuff
}

function stopLoop() {
    window.clearInterval(int);
}
+4
source

All Articles