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

时间:2019-04-19 02:17:33

标签: javascript jquery css twitter-bootstrap

我希望在点击链接后获得2分钟的计时器。

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

有人可以帮忙吗?

关于, 比尔

3 个答案:

答案 0 :(得分:2)

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

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);
  }
}

我编辑我的答案

答案 1 :(得分:0)

尝试一下:

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>

答案 2 :(得分:0)

您好,您可以使用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>