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; } }
2/22/2021 9:37:24 AM
Anouk Moyal
10 Answers
New Answerinfinite 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; } }
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...
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.
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?
yes: you could avoid i and use input (seconds): while (0 <= seconds) { console.log(seconds); --seconds; }
function main() { var seconds = parseInt(readLine(), 10) // Your code here while(seconds>=0){ console.log(seconds) seconds -- } }
function main() { var seconds = parseInt(readLine(), 10) // Your code here while (seconds>=0){ console.log(seconds); seconds--; } }
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--)} }
function main() { var seconds = parseInt(readLine(), 10) // Your code here var i=0; while(i<=seconds){ console.log(seconds); --seconds; } }