This is my code. What I want it to do is write 0, wait one sec, write 1, wait one sec, write 2, wait one sec, etc. Instead it writes 5 5 5 5 5
for(i = 0; i < 5; i++) {
setTimeout("document.write(i + ' ')", 1000);
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
1) You set all the timeouts to last 1 second at the same time. The loop doesn’t wait for the timeout to occur. So you have 5 timeouts that all execute at the same time.
2) When the timeouts execute, the loop is long since complete and
ihas become 5. So once they execute, they all print “5”3)
document.write()writes somthing onto the page, in the same place it executes. I.e. if you have<script>document.write("xyz")</script>in the middle of a piece of text, it’ll write “xyz” in the middle of the text. The timeouts, however, are not necessarily anywhere on the page. They exist only in code.Here’s a solution that’s as close to yours as possible: http://jsfiddle.net/rvbtU/1/
However, that solution uses setTimeout’s ability to evaluate a string as javascript, which is never a good idea.
Here’s a solution that uses an anymous function instead: http://jsfiddle.net/YbPVX/1/
Edit: Forgot to save the 2nd fiddle. Whoops. Fixed now.