<script>
var timer = 0;
function SpellItOut(word)
{
var temp = word[timer];
timer += 1;
//why does this line alert the string 'temp' that i pased to it?
setTimeout("alert('temp')",2000);
//but this one does not alert the string stored in var temp?
setTimeout("alert(temp)",2000);
}
</script>
<p><a href="javascript:SpellItOut('welcome')">welcome</a></p>
<script>
var timer = 0;
function SpellItOut(word)
{
var temp = word[timer];
timer += 1;
if( timer >= word.length ){ timer = 0; }
alert(temp);
setTimeout("alert(temp)",2000);
}
</script>
<p><a href="javascript:SpellItOut('welcome')">welcome</a></p>
in the code above why does
Code:
alert(temp);
spell out the word each time i click the link, but
Code:
setTimeout("alert(temp)",2000);
not do the same thing 2 seconds later, the setTimeOut doesn't work at all, but it should run the same alert() that is executing on the line right above it?
Last edited by bsmbahamas; 04-10-2010 at 07:09 PM.
Because when you pass a string to setTimeout, it executes in global scope. That means that only global variables are accessible. So one bad option would be to make temp a global variable, but a better option would be this.
Code:
setTimeout(function(){alert(temp);},2000);
You should never pass a string to setTimeout, always use a function instead.
Great wit and madness are near allied, and fine a line their bounds divide.
Because when you pass a string to setTimeout, it executes in global scope. That means that only global variables are accessible. So one bad option would be to make temp a global variable, but a better option would be this.
Code:
setTimeout(function(){alert(temp);},2000);
You should never pass a string to setTimeout, always use a function instead.
i'll modify and try again, and i guess that means i shuld have titled this post setTimeout() not working properly too, lol
Bookmarks