I have read many topics about setTimeout
but still i have a problem in understanding how can i implement this function to my loop.
I'll try to show you what I mean.
function RandomHit(anyArray)
{
var turechange = false;
do{
setTimeout(function(){
var random = Math.floor(Math.random()*2);
if(random===0)
{
turechange = true;
console.log(random);
}
if(random===1)
{
console.log(random);
}
}, 2000);
}while(!turechange);
}
Every time when the loop goes again, i try slow down code for a 2000 ms. But this doesn't work.
I have read many topics about setTimeout
but still i have a problem in understanding how can i implement this function to my loop.
I'll try to show you what I mean.
function RandomHit(anyArray)
{
var turechange = false;
do{
setTimeout(function(){
var random = Math.floor(Math.random()*2);
if(random===0)
{
turechange = true;
console.log(random);
}
if(random===1)
{
console.log(random);
}
}, 2000);
}while(!turechange);
}
Every time when the loop goes again, i try slow down code for a 2000 ms. But this doesn't work.
Share Improve this question edited Mar 23, 2014 at 11:35 Davin Tryon 67.3k15 gold badges147 silver badges137 bronze badges asked Mar 23, 2014 at 11:30 Dariusz PlichtaDariusz Plichta 451 silver badge6 bronze badges 2- See eg stackoverflow./questions/22584035/…, that appears to be essentially the same question – Håkan Lindqvist Commented Mar 23, 2014 at 11:35
-
I am not clear with your question, but you should use
setInterval()
andclearInterval()
instead ofloop
andsetTimeout()
– Tun Zarni Kyaw Commented Mar 23, 2014 at 11:36
1 Answer
Reset to default 7You have a problem with the one threaded nature of JavaScript (at least in this case - there are some exceptions, though).
What actually happens in your code is an endless while
loop inside, in which plenty of setTimeout()
functions are queued up. But as your code never actually leaves the while
loop, those callbacks wont be executed.
One solution would be to trigger the next timeout function inside the setTimeout()
callback like this:
function RandomHit(anyArray) {
var turechange = false;
function timerFct(){
var random = Math.floor(Math.random()*2);
if(random===0)
{
turechange = true;
console.log(random);
}
if(random===1)
{
console.log(random);
}
if( !turechange ) {
setTimeout( timerfct, 2000 );
}
}
timerFct();
}
An alternative solution would be to use setIntervall()
and clearIntervall()
:
function RandomHit(anyArray)
{
function timerFct(){
var random = Math.floor(Math.random()*2);
if(random===0)
{
turechange = true;
console.log(random);
}
if(random===1)
{
console.log(random);
}
if( turechange ) {
clearTimeout( timeoutHandler );
}
}
var turechange = false,
timeoutHandler = setInterval( timerFct, 2000 );
}