简体   繁体   中英

Javascript linking a function to the click of a button

I am to invoke a timer using the click of a button. Function for timer:

function countDown(seconds, elem){
    var element = document.getElementById(elem);
    element.innerHTML = "Please wait for "+seconds+ " seconds";

    if(seconds < 1){
        clearTimeout(timer);
        element.innerHTML ='<h2> You can let Go, Frist Responders have been informed</h2>';
    }
    seconds--;

    var timer = setTimeout('countDown('+seconds+',"'+elem+'")',1000); 
}

Function call:

document.querySelector('body').onClick = countDown(5,"para");

HTML:

<div class="wrapper" id="butt2">
<button id="butt" class="fade-in-fwd" >SOS</button>
</div>

<p id="para"></p>

This starts running the timer as soon as the webpage loads. How do I limit this

There are couple of issues in your code:

  1. onClick should be written as onclick
  2. onclick requires a function that will be triggered on click. Since you have assigned countDown(5,"para") in the onclick , it is invoked immediately.

 document.querySelector('body').onclick = function(){ countDown(5,"para"); } function countDown(seconds, elem) { var element = document.getElementById(elem); element.innerHTML = "Please wait for " + seconds + " seconds"; if (seconds < 1) { clearTimeout(timer); element.innerHTML = '<h2> You can let Go, Frist Responders have been informed</h2>'; } seconds--; var timer = setTimeout('countDown(' + seconds + ',"' + elem + '")', 1000); } 
 <div class="wrapper" id="butt2"> <button id="butt" class="fade-in-fwd">SOS</button> </div> <p id="para"></p> 

Note that there will be weird behaviour with this code if you click multiple times as timer is reinitialized without clearing the previous one so you need to handle that too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM