I want to stop a loop in a function from another function in JavaScript. Here is the code that 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/
You use the break statement to terminate a loop early such as the while loop or the for loop. If there are nested loops, the break statement will terminate the innermost loop. You can also use the break statement to terminate a switch statement or a labeled statement.
A for..in loop can't use break. It's not possible to end it in this way.
Functions in JavaScript can be exited by using return , break or throw . Functions in JavaScript always return something even if not explicitly stated. Behind the scenes, the return statement is implicit if it hasn't been provided. The default return value for a function is undefined.
This var static loop = 1;
is invalid, var loop = 1;
, but you start an infinite loop, so you won't be able to stop it this way.
Use setInterval instead
var int = self.setInterval(function(){myLoop()},100);
function myLoop() {
//do stuff
}
function stopLoop() {
window.clearInterval(int);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With