Question: I'm having a problem that I can't solve. I have a loop in javascript where the condition variable to stop depends on a global variable. The loop starts looping and when I change the value of that global variable it never stops.

```
stop = false;
var i = 0;
while ((stop == false) && (i<100000)){
    console.log("hi-"+i);
    i++;
}

```

While loop is running, if I do stop = true, it never stops. I do not know why is that.

Any idea?

Thanks!

Answer: 
JavaScript is inherently single threaded. Once a block of code has started running, it will run to completion before anything else happens. IE the event where you're setting `stop` to `true` will not execute until after the while loop has finished.

You need to split your loop into sections and run each section individually, allowing other events to take place:

```
stop = false;
var i = 0;

function loopLogic() {
  var tempStop = i + 500;
  while (i < tempStop) {
    //original processing logic
    console.log("hi-" + i);
    i++;
  }

  if (!stop && i < 100000)
    window.setTimeout(loopLogic, 0);

}
window.setTimeout(loopLogic, 0);

```

This breaks up the function into multiple chunks of 500 at a time. The `setTimeout` of 0 duration lets the function continue (almost) immediately, but will put the next chunk at the bottom of the execution chain. This allows other events to happen and therefore will allow updating of `stop` to `true`

[Here's a fiddle](http://jsfiddle.net/98y294m7/1/) showing this approach.

The other approach available in compliant browsers is the [Web Worker](http://en.wikipedia.org/wiki/Web_worker), but that's starting to get beyond the scope of this question.
You can try using the setInterval....
Put what you need to do into a function and call it at some interval...
Take a look here...

<http://jsfiddle.net/o5mnb7jv/1/>

```
var stop = false;
var obj = document.getElementById("btn").addEventListener("click", function(){
    stop = true;
});
var interval;
function loop(){
    var result = document.getElementById("result");
    if(!stop){
        result.innerHTML = "Running...";
    }else{
        clearInterval(interval);
        result.innerHTML = "Stopped...";
    }
}
interval = setInterval(loop, 500);

```