Jump to content

settimeout not working


sastro

Recommended Posts

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

Link to comment
Share on other sites

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. 

 

Link to comment
Share on other sites

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>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.