Enable button when counter reaches zero

杀马特。学长 韩版系。学妹 提交于 2019-12-08 05:34:25

This is much simpler than what you've got. Just use window.setTimeout().

Keep in mind that tracking time to a high precision is not super reliable in a browser. You may want to look at moment.js or use performance.now() for an easier API to handle that.

// Get refreence to span and button
var spn = document.getElementById("count");
var btn = document.getElementById("btnCounter");

var count = 5;     // Set count
var timer = null;  // For referencing the timer

(function countDown(){
  // Display counter and start counting down
  spn.textContent = count;
  
  // Run the function again every second if the count is not zero
  if(count !== 0){
    timer = setTimeout(countDown, 1000);
    count--; // decrease the timer
  } else {
    // Enable the button
    btn.removeAttribute("disabled");
  }
}());
<button id="btnCounter" disabled>Time left: <span id="count"></span></button>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!