+ 2

Begginer JavaScript help!

Hello Everyone, Brand new coder here. As I've been finishing up the Javascript tutorial I have been giving myself small challenges as a sort of skillcheck. I'm trying to write a very simple script that counts from 1 to 20 with a 1 second pause before it writes each number. Why isn't my code achieving this task?? var count = 0; var delay = 1000; function counter () { while (count < 20) { count += 1; document.write(count); if (count > 0) { set.Timedelay(counter, delay); }} } counter(); I've tried writing this many different ways with many different loops and I'm just not getting it. Sorry for the formatting I'm brand new to this.

23rd May 2018, 8:32 AM
C M
C M - avatar
6 Answers
+ 6
C M , Let me explain the problem with your code. When you first call the counter function, it is executed this way: The while loop will be executed in a matter of milliseconds. After that: count var is already 20, the numbers 1-20 is already written in the document, and you have 20 pending setInterval calls. Obviously, after a complete second, they will start. But they will immediately end because count var is already 20. Here's a working code: https://code.sololearn.com/Wi8FwG76S3ze/?ref=app
23rd May 2018, 10:49 AM
Jonathan Pizarra (JS Challenger)
Jonathan Pizarra (JS Challenger) - avatar
+ 3
C M can you please provide a code link so that we can help you. I have never encountered a set.Timedelay() predefined in JavaScript. Are you using a framework?
23rd May 2018, 9:18 AM
Jonathan Pizarra (JS Challenger)
Jonathan Pizarra (JS Challenger) - avatar
+ 3
You're welcome C M 👍
23rd May 2018, 10:59 AM
Jonathan Pizarra (JS Challenger)
Jonathan Pizarra (JS Challenger) - avatar
+ 1
Jonathan Pizarra Very good breakdown of the explanation. I clearly didn't have a good understanding of how loops work. I've saved both explanations for my notes. Thanks a ton guys! I know now how the setinterval function works!
23rd May 2018, 10:58 AM
C M
C M - avatar
0
https://code.sololearn.com/Wp6r4o5x9ZTX/?ref=app thanks for your reply! I've linked what I'm trying to do. as you can see, the set.timedelay is being ignored. I'm just trying to figure out what I'm doing wrong! haha
23rd May 2018, 9:38 AM
C M
C M - avatar
0
Ray Chuah awesome! thank you very much. I didn't know that the setInterval was a loop in itself. definitely chose a task outside of my realm of knowledge. thank you for breaking this down.
23rd May 2018, 10:43 AM
C M
C M - avatar