So I have a checkbox. And I am trying to make it so that when you click the checkbox, it shows a message, pauses, and then does another thing. I know you can use setInterval
or setTimeout
– I am using setTimeout
. Anyways, enough waffling, here is the JavaScript code:
function real() {
if (checker2.checked == true) {
setTimeout(function() {
checker2.disabled = true
const p = document.createElement("p")
p.innerHTML = "Yes! You are human (or at least have a 99.9% of being)"
document.body.appendChild(p)
p.style.color = "white"
}, 5000)
console.log("This should print after 5 seconds")
}
}
The problem isn’t the checkbox or anything like that the problem is it doesn’t pause for five seconds. It just skips straight to printing it. I’m not sure what’s wrong. I appreciate help. Thanks
3
Answers
Change your code to this:
as only the callback function, you give to
setTimeout()
as parameter, will be executed after 5 seconds and not the following code.I think you’re misunderstanding how setTimeout works. The function inside
setTimeout()
will be executed once the timer expires.The following should be working as you expect it:
If you want to delay your print statement, it must be inside
setTimeout
as a callback. See the following example.