Javascript Execution Time Out | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Javascript Execution Time Out

I'm having problems with the while loop - everytime I think I got it, theres an Execution Timed Out error message. This is the exercize: Write a program-timer, that will take the count of seconds as input and output to the console all the seconds until timer stops. This is my code: function main() { var seconds = parseInt(readLine(), 10) // Your code here var i = 0 while (i <= 24){ console.log(i); i=seconds-1; } }

22nd Feb 2021, 9:37 AM
Anouk Moyal
Anouk Moyal - avatar
10 Answers
+ 2
infinite loop... until your input is greater than 25... you update i value with seconds-1 wich is constant ^^ you should test while (i <= seconds) and increment i: function main() { var seconds = parseInt(readLine(),10); var i = 0; while (i < seconds) { console.log(i), ++i; } }
22nd Feb 2021, 9:52 AM
visph
visph - avatar
+ 2
Since i=0, and i<=24 is always true, because seconds values not changing ,hence i = seconds-1 is also always same. So while loop becomes infinite loop.. so you get time out...
22nd Feb 2021, 9:53 AM
Jayakrishna 🇮🇳
+ 1
This is an infinite loop. The program never ends executing. Suppose seconds variable is 10. i will always be 9. And 9 is less than 24, making the condition is always true and thus infinite loop occurs.
22nd Feb 2021, 9:52 AM
你知道規則,我也是
你知道規則,我也是 - avatar
+ 1
Thank you guys! I tried visph code and I don't get an error code now which is nice...though is there a way to count down from the input number instead of count up from 0?
22nd Feb 2021, 10:06 AM
Anouk Moyal
Anouk Moyal - avatar
+ 1
yes: you could avoid i and use input (seconds): while (0 <= seconds) { console.log(seconds); --seconds; }
22nd Feb 2021, 10:08 AM
visph
visph - avatar
+ 1
function main() { var seconds = parseInt(readLine(), 10) // Your code here while(seconds>=0){ console.log(seconds) seconds -- } }
17th Jun 2021, 10:25 AM
Agon Istrefi
0
Thank you so much, I got it!
22nd Feb 2021, 10:10 AM
Anouk Moyal
Anouk Moyal - avatar
0
function main() { var seconds = parseInt(readLine(), 10) // Your code here while (seconds>=0){ console.log(seconds); seconds--; } }
15th Nov 2021, 12:34 PM
MD RAKIBUL HASSAN NAYON
MD RAKIBUL HASSAN NAYON - avatar
0
Any remarks? This outcome seems to work too... function main() { var seconds = parseInt(readLine(), 10) var i = 0 // Your code here while (i<=seconds){console.log (seconds--)} }
8th Dec 2021, 9:41 AM
N C
N C - avatar
- 1
function main() { var seconds = parseInt(readLine(), 10) // Your code here var i=0; while(i<=seconds){ console.log(seconds); --seconds; } }
25th Jun 2021, 10:06 PM
Abiel M
Abiel M - avatar