WeChat development is becoming more and more popular now. The countdown function is a relatively common function, such as users need to use it to obtain verification codes. The countdown function is often used in project development. Today I will introduce to you the implementation code of the countdown function in the WeChat applet. Friends who need it can refer to it. I hope it can help you.
Let’s look at the code directly
//倒计时60秒 function countDown(that,count) { if (count == 0) { that.setData({ timeCountDownTop: '获取验证码', counting:false }) return; } that.setData({ counting:true, timeCountDownTop: count + '秒后重新获取', }) setTimeout(function(){ count--; countDown(that, count); }, 1000); }
Call where the countdown is required
Page({ data:{ counting:false }, //生成验证码 generateVerifyCode:function() { var that = this; if (!that.data.counting) { wx.showToast({ title: '验证码已发送', }) //开始倒计时60秒 countDown(that, 60); } }, })
The following is a brief introduction to the implementation of the function
The first way to count down is to write Outside of Page, this is not a mistake.
The key to implementing the countdown is the setTimeout method, which is the following code. The setTimeout method can set a function to be executed at a specified time interval. The applied format is setTimeout(function(), time), function is the corresponding method to be executed, time is the time interval, where 1000 means 1000 milliseconds, that is, the countDown method is executed every 1 second.
setTimeout(function(){ count--; countDown(that, count); }, 1000);
In the countDown method, use the count field to set the countdown time, for example, here is 60 seconds.
In the countDown method, that is also passed in The purpose is to use the setData method to update the page when the countdown status changes
The counting field is used in the countDown method to determine whether the countdown is already in progress and to avoid starting the countdown repeatedly
The end of the countdown is judged by count, and you can exit directly by return
Related recommendations:
Send verification code countdown function when registering with mobile phone
JavaScript minute and second countdown timer implementation method
Produce a vue-based countdown demo
The above is the detailed content of Example to explain the countdown function of WeChat applet. For more information, please follow other related articles on the PHP Chinese website!