skip to Main Content

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


  1. Change your code to this:

    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"
                console.log("This should print after 5 seconds")},5000)
    }}
    

    as only the callback function, you give to setTimeout() as parameter, will be executed after 5 seconds and not the following code.

    Login or Signup to reply.
  2. 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:

    function real() {
      if (checker2.checked == true) {
    
          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"
    
          setTimeout(function() {
              console.log("This should print after 5 seconds")
          }, 5000)
        
      }
    }
    
    Login or Signup to reply.
  3. If you want to delay your print statement, it must be inside setTimeout as a callback. See the following example.

    function real() {
      if (document.getElementById("checker2").checked) {
    
        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";
    
        setTimeout(function() {
          console.log("This should print after 5 seconds")
        }, 5000);
    
      }
    }
    <input type="checkbox" id="checker2" name="checker2" value="Check it" onClick="real()">
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search