+ 1

Can anyone explain to me why this timer works perfect in chrome console and w3schools console but not on SL? Thanks for response

https://code.sololearn.com/W3K0Z249Z9w4/?ref=app https://code.sololearn.com/Wl9BRXxloQZz/?ref=app Neither work, both give same error only in SL console though. It keeps giving me 'Uncaught TypeError: Cannot set property 'innerHTML' of null line: 7'. It is supposed to count down from 30.

17th Jun 2017, 4:08 AM
Dustin Hammack
Dustin Hammack - avatar
4 ответов
+ 3
SoloLearns compiler will load the global variables from the javascript code before the body tags. So the element by that id couldn't be found. Doing something like this instead works for me: (Or, maybe initialize the tag variable inside a function) <p id="timer">30</p> <script> var tag = document.getElementById('timer'); var x = 30; var timerText = setInterval(function() { x -= 1; tag.innerHTML = x; }, 1000) var timerSet = setTimeout(function() { clearInterval(timerText); }, 31000) </script>
17th Jun 2017, 4:20 AM
Rrestoring faith
Rrestoring faith - avatar
+ 2
Sololearn loads the JS code in the head tag. So the DOM access function would not work before the page fully loaded. You can work around this in JS pane, by letting window.onload call your DOM access function. window.onload = main; function main (){ // your DOM access codes } To prove that Sololearn loads the JS code in head tag, we can open Chrome developer studio (Contol-alt-i) to view the console output. When the Run button is clicked, Sololearn outputs the compiled code from console.log
17th Jun 2017, 5:20 AM
Calviղ
Calviղ - avatar
+ 1
wow, just realized. Instead of separating the files I had to just add the script code to the bottom of the html file and it fixed. The "Basic Timer " program link above now shows the working version.
17th Jun 2017, 4:28 AM
Dustin Hammack
Dustin Hammack - avatar
+ 1
I fixed it without making another <script>. https://code.sololearn.com/WD2ovi4WYQ9p/?ref=app
26th Jun 2017, 1:21 PM
TheCoder
TheCoder - avatar