sastro Posted October 19, 2010 Share Posted October 19, 2010 Here is the code <script language="Javascript"> var n=""; var x=0; var de=0; for(i=0;i<20;i++){ n=n+'-'+i; x=x+1; if(x==5){ de=de+5000; setTimeout("alert(n)",de); n=""; x=0; } } </script> Why the alert result empty? It should be 4 times alerts every 5 seconds with -1-2-3-4-5 -6-7-8-9-10 -11-12-13-14-15 -16-17-18-19-20 Please help Quote Link to comment https://forums.phpfreaks.com/topic/216261-settimeout-not-working/ Share on other sites More sharing options...
.josh Posted October 19, 2010 Share Posted October 19, 2010 You do n=""; every 5th loop iteration. By the time setTimeout actually performs the alert even the first time, the for loop is already finished and the final value of n is "". So it just alerts a blank string every time. setTimeout does not take what the value currently is at the time (a "snapshot", if you will) and put it in some queue. When the alert happens, it takes the current value of n. The overall principle to understand is that setTimeout is not like "pausing" the script (what most languages would call "sleep"). It is asynchronous, meaning it bumps the specified code in the first argument back X amount of time (specified by 2nd argument), but continues to execute other code on the page. Quote Link to comment https://forums.phpfreaks.com/topic/216261-settimeout-not-working/#findComment-1123971 Share on other sites More sharing options...
sastro Posted October 19, 2010 Author Share Posted October 19, 2010 Thanks for reply. Found the solution <script language="Javascript"> var n=""; var x=0; var de=0; for(i=0;i<20;i++){ n=n+'-'+i; x=x+1; if(x==5){ de=de+1000; j=n+' - '; setTimeout(function (x){return function(){alert(x)};}(j),de); x=0; n=""; } } </script> Quote Link to comment https://forums.phpfreaks.com/topic/216261-settimeout-not-working/#findComment-1124012 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.