Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop a loop in a function from another function in JavaScript

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/

like image 526
MHDaouas Avatar asked Apr 10 '13 14:04

MHDaouas


People also ask

How do you stop a loop in JavaScript?

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.

Can we break for of loop in JavaScript?

A for..in loop can't use break. It's not possible to end it in this way.

How do you break a function in JavaScript?

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.


1 Answers

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);
}
like image 83
Philippe Boissonneault Avatar answered Sep 21 '22 22:09

Philippe Boissonneault