I’m using this button: <div class="but durationcell" id="but5"><input type="button" value="5"></div>
…to change a div to yellow, then with the below functions, at 5 secs turn to green, then at 5 secs back to red. (like a stoplight.)
However, the console says “Uncaught TypeError: yellow5.addEventListener is not a function” and “Uncaught TypeError: window.location is not a function”
I don’t know what else to do to fix this, after trying other code examples. Must be something simple I’m missing.
<script>
function yellow5() {
var yel = document.getElementById("colorwindow");
yel.style.backgroundColor="yellow";
setTimeout(function(){
green(); // goes to function to turn div green
}, 5000);
}
yellow5.addEventListener('click', but5);
function green() {
var green = document.getElementById("colorwindow");
green.style.backgroundColor="green";
setTimeout(function(){
reset(); // goes to function to reset the page (turns off everything and sets div to red)
}, 5000);
}
function reset() {
window.location("testing-yellow-red-lights.html");
}
</script>
EDIT: I see that the window.location should be: window.location.href="testing-yellow-red-lights.html";
How do I use clearTimeout in the reset button for clearing the setTimeouts of any of my buttons? I can’t find a usage that matches my above implementation.
If you look at the MDN page for setTimeout you will see Return Value reads as follows:
The returned timeoutID is a positive integer value which identifies the timer created by the call to setTimeout() . This value can be passed to clearTimeout() to cancel the timeout.
So in answer you could either use a global, or alternatively pass the timeoutID to the next function. For example:
function backgroundToYellow () {
const colorWindow = document.getElementById('colorwindow')
colorWindow.style.backgroundColor = 'yellow'
// assign the returned timeoutId and setup a colour change in 5 seconds
const timeoutId = setTimeout(() => backgroundToGreen(), 5000)
// call the cancel function in 1 second passing in the timeoutId
setTimeout(() => cancelChangeToGreen(timeoutId), 1000)
}
function backgroundToGreen () { ... }
function cancelChangeToGreen(timeoutId) {
clearTimeout(timeoutId) // prevent a call to backgroundToGreen from happening
}
Here is a codepen. I have used setInterval and clearInterval to more clearly illustrate this.
Practicing for sure! But the reset code I used did not stop the timer, so it did nothing. That’s why I think clearTimeout is needed, not just a paint job.