Note that there are some explanatory texts on larger screens.

plurals
  1. POsetTimeout inside for loop & Scope resolution issue
    primarykey
    data
    text
    <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/8070896/how-to-use-settimeout-in-a-for-loop">How to Use setTimeout in a for&hellip;loop</a><br> <a href="https://stackoverflow.com/questions/10020127/calling-settimeout-with-a-for-loop">calling setTimeout with a for loop</a> </p> </blockquote> <p>For me, <code>setTimeout</code> function doesn't work inside for loop. It executes after all for loop statements are executed.</p> <p>I am facing with this scope issue in case of <code>setTimeout</code> function in javascript.</p> <p>Here's my code snippet ..</p> <pre><code> ... moves[] is an array .. for(i=0;i&lt;noOfMoves;i++) { playerName = moves[i].playerName; timeDiff = moves[i].timeDiff; console.log("Inside for loop"+ playerName); setTimeout(function(){ console.log("Inside set time out :"+playerName); },timeDiff); .... .... } </code></pre> <p>But it awkwardly prints out the following output ...</p> <pre><code> Inside for loopplayer1 Inside for loopplayer2 Inside for loopplayer3 Inside for loopplayer4 .... (noOfMoeves times .. ) Inside set time outplayer1 Inside set time outplayer1 Inside set time outplayer1 Inside set time outplayer1 </code></pre> <p><strong>EDIT :</strong></p> <p>I am wanting o/p of following way</p> <p>I am expecting the code to go line by line .. printing "<code>Inside for loop</code>" console log first, then wait for "<code>timeDiff</code>" period and then print the "<code>Inside settimeout</code>" function console log .. how can i do that ? –</p> <pre><code> Inside for loopplayer1 Inside set time outplayer1 // (after waiting for timeDiff time) Inside for loopplayer2 Inside set time outplayer2 // (after waiting for timeDiff time) ...... ...... </code></pre> <p>Also, playerName variable is getting same value in each settimeout console log statement ?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload