Execute sentences for a period of time

1

I want the console.log('ejecutando'); statement to be executed repeatedly for a certain time. At the end of that interval, having set the flag in false , the execution should end.

My solution does not work. Why?

var bandera = true;
setTimeout(function () {
    bandera = false;
}, 60000);

while (bandera ) {
   console.log('ejecutando');
}
    
asked by hubman 13.10.2017 в 01:08
source

2 answers

1

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);
    
answered by 13.10.2017 / 01:58
source
2

The reason is very simple:

JavaScript runs on a single thread.

Therefore the code within the setTimeOut that waits to be executed is blocked by the while infinite, in a few words until the execution of that while is not finished, the event can not be executed, even to despite having already finished the time (60s).

Therefore bandera is never set in false and the loop never ends.

Moral:

That the setTimeout run in asynchronous does not mean that it is executed in another thread.

    
answered by 13.10.2017 в 01:50