Home > Web Front-end > JS Tutorial > JS method to implement countdown effect based on recursion

JS method to implement countdown effect based on recursion

高洛峰
Release: 2016-12-05 11:12:12
Original
1818 people have browsed it

The example in this article describes the method of using JS to implement the countdown effect based on recursion. Share it with everyone for your reference, the details are as follows:

Event:

//发送验证码
$('.js-sms-code').click(function(){
    $(this).attr("disabled", "disabled").html("<span style=&#39;color:#666&#39;><span id=&#39;countdown&#39;>60</span>s 后再试</span>");
    countdown();
    var tel = $(&#39;#tel&#39;).val();
    $.ajax({
      url: "{sh::U(&#39;Home/sendSmscode&#39;)}",
      type:&#39;POST&#39;,
      dataType:"json",
      data: {tel: tel},
      success: function() {
      },
      error: function() {
        $(&#39;.js-help-info&#39;).html("请求失败");
      }
    });
})
Copy after login

Comments: The countdown method here is the beauty.

Look at the code:

function countdown() { // 递归
  setTimeout(function() {
    var time = $("#countdown").text();
    if (time == 1) {
      $(&#39;.js-sms-code&#39;).removeAttr("disabled");
      $(&#39;.js-sms-code&#39;).html("发送验证码");
    } else {
      $("#countdown").text(time - 1);
      countdown();
    }
  }, 1000);
}
Copy after login

Comments: If time is not equal to 1, continue to call and subtract one second from the time. setTimeout is also very essential. Until the time decreases to 1, remove disabled and change the content to 'send verification code'.


Related labels:
js
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template