The javascript interpreter is not multithreaded , therefore it is not possible to modify the value of bandera
while waiting / executing other sentences (in this case the while), resulting in an infinite loop.
You can easily see this in the following script:
setTimeout(function () {
console.log("STOP!");
}, 1);
for(let i=0; i<200000; i++) {
console.log('ejecutando '+i);
}
Regardless of the time interval you define in setTimeout
, you will end up spacing for the operation that lasts longer between the defined interval and the other blocking operation .
As you can see the end of the interval is executed after 200 thousand executions of console.log
, despite having indicated 1 millisecond delay.
What would be a correct solution to the problem?
- You can use setInterval () to execute a set of sentences every certain time, in this case, always
- Then, use setTimeout () to stop the execution of
setInterval
by clearInterval()
// Ejecuto siempre..
let interval = setInterval(function(){
console.log("Ejecutando...");
}, 0);
// A los 2 segundos cancelo ejecucion
setTimeout(function(){
clearInterval(interval);
console.log('FIN');
}, 2000);