简体   繁体   English

如何在点击时启动计时器?

[英]How to start a timer on click?

I am looking to get a 2 minutes timer on click of a link.我希望通过单击链接获得 2 分钟的计时器。

 <a href="javascript:void(1);">Resend code</a>

Can anyone help?任何人都可以帮忙吗?

Regards, Bill问候, 比尔

<button id = "timerButton" onclick = "myTimer()">Resend code</button>

javascript code javascript代码

let cTime = 120;
function myTimer(){
  if(cTime == 0){
    document.getElementById("timerButton").innerHTML = "Resend code";
  } else{
    document.getElementById("timerButton").innerHTML = cTime;
    cTime = cTime - 1;
    setTimeout(myTimer, 1000);
  }
}

I edit my answer我编辑我的答案

Try this:尝试这个:

 var mins; var secs; var interval; $(document).ready(function() { $("#send-code").click(function() { mins = 2; secs = 0; var btn = $(this); btn.attr("disabled", true); interval = setInterval(function() { if (mins >= 0 && secs >= 0) { btn.text("Resend Code in " + pad(mins, 2) + ":" + pad(secs, 2)); if (secs > 0) { secs--; } else { secs = 59; mins--; } if (mins < 0) { clearInterval(interval); btn.removeAttr("disabled").text("Send Code"); return true; } } console.log("Mins: " + mins + ", Secs: " + secs); }, 1000); }); }); function pad(num, size) { var s = num + ""; while (s.length < size) s = "0" + s; return s; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="send-code">Send Code</button>

Hello you can use countdown function and change the time you want in js-startTimer function您好,您可以使用countdown功能并在js-startTimer功能中更改您想要的时间

 var interval; function countdown() { clearInterval(interval); interval = setInterval( function() { var timer = $('.js-timeout').html(); timer = timer.split(':'); var minutes = timer[0]; var seconds = timer[1]; seconds -= 1; if (minutes < 0) return; else if (seconds < 0 && minutes != 0) { minutes -= 1; seconds = 59; } else if (seconds < 10 && length.seconds != 2) seconds = '0' + seconds; $('.js-timeout').html(minutes + ':' + seconds); if (minutes == 0 && seconds == 0) clearInterval(interval); }, 1000); } $('#js-startTimer').click(function () { $('.js-timeout').text("2:00"); countdown(); });
 <p>2 minutes timer <span class="js-timeout">2:00</span>.</p> <button id="js-startTimer">Start Countdown</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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