简体   繁体   中英

Trouble linking javascript to html button

I am making a 10-second countdown for a game using Javascript/HTML. At this time the code runs at load. But, the thing is I am having trouble linking it to a button so that I can have the code fire off onclick.

 function countdown(secs,elem){ var element= document.getElementById(elem); element.innerHTML = "Time is running out.." +secs+ " seconds"; secs--; var timer = setTimeout('countdown('+secs+' ,"'+elem+'")',1000); if (secs<1) { clearTimeout(timer); element.innerHTML="<h1> GAME OVER!</h1>"; }; } 
 <div class="clock"> <div id="status"></div> <script type="text/javascript">countdown(10,"status");</script> </div> 

I have tried a lot of different thing but just can't seem to get it to work. Any help would be great. Thanks

  function countdown(secs, elem) { var element = document.getElementById(elem); element.innerHTML = "Time is running out.." + secs + " seconds"; secs--; var timer = setTimeout('countdown(' + secs + ' ,"' + elem + '")', 1000); if (secs < 1) { clearTimeout(timer); element.innerHTML = "<h1> GAME OVER!</h1>"; }; } 
 <div class="clock"> <div id="status"></div> <button onclick="countdown(10,'status');">Click Me</button> </div> 

try this, you can follow this tutorial for refrence

 function countdown(secs, elem) { var element = document.getElementById(elem); element.innerHTML = "Time is running out.." + secs + " seconds"; secs--; var timer = setTimeout('countdown(' + secs + ' ,"' + elem + '")', 1000); if (secs < 1) { clearTimeout(timer); element.innerHTML = "<h1> GAME OVER!</h1>"; }; } 
 <div class="clock"> <div id="status"></div> </div> <button onclick="countdown(10,'status')">start</button> 

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