+ 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.
4 Respostas
+ 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>
+ 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
+ 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.
+ 1
I fixed it without making another <script>.
https://code.sololearn.com/WD2ovi4WYQ9p/?ref=app