How to set a timer? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to set a timer?

Hi! I have two questions: 1) Why do I need to write "[0]:" to make my code working? 2) Why is "setTimeout function" doesn't work? Here's the code <html> <body> <div class="container">Hi there! My name is container</div> <style> body { background-color: #333 } .container { background-color: #000; color: #fff; padding: 10px; text-align: center;} </style> <script> window.onload = function colorChanger() { var changeColor = document.getElementsByClassName("container"); changeColor[0].style.color = "#000"; changeColor[0].style.backgroundColor = "#fff"; }; setTimeout(colorChanger, 5000); </script> </body> </html> Thanks for advance

31st Oct 2017, 4:51 AM
selipasha
selipasha - avatar
3 Answers
+ 4
For question part 2 * window.onload runs the function immediately (this is not just a declaration; it's code to auto-run) * the name colorChanger() is not in scope for setTimeout * if it were in scope, it has already run once and there's no difference in the next run. This puts the function in the global scope with optional use in onload: function colorChanger() { // alert("changing color..."); // to test var changeColor = document.getElementsByClassName("container"); changeColor[0].style.color = "#000"; changeColor[0].style.backgroundColor = "#fff"; }; // window.onload = colorChanger; // if you want to test setTimeout(colorChanger, 5000);
31st Oct 2017, 5:09 AM
Kirk Schafer
Kirk Schafer - avatar
+ 1
Thanks you all guys
31st Oct 2017, 5:23 AM
selipasha
selipasha - avatar
- 2
Not working
31st Oct 2017, 5:03 AM
selipasha
selipasha - avatar