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='color:#666'><span id='countdown'>60</span>s 后再试</span>"); countdown(); var tel = $('#tel').val(); $.ajax({ url: "{sh::U('Home/sendSmscode')}", type:'POST', dataType:"json", data: {tel: tel}, success: function() { }, error: function() { $('.js-help-info').html("请求失败"); } }); })
Comments: The countdown method here is the beauty.
Look at the code:
function countdown() { // 递归 setTimeout(function() { var time = $("#countdown").text(); if (time == 1) { $('.js-sms-code').removeAttr("disabled"); $('.js-sms-code').html("发送验证码"); } else { $("#countdown").text(time - 1); countdown(); } }, 1000); }
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'.