Usually when developing WeChat mini-programs, countdown is essential due to project needs. The following mainly explains the use of timers in WeChat mini-programs.
One thing we need to declare here is that this article mainly implements the countdown function, and the implementation is a countdown with a shorter time, and other optimizations are not mainly considered.
If we achieve a simple 60s countdown effect, we can use setInterval directly, but in the WeChat applet, we need to use the syntax of the WeChat applet, and we will encounter a problem, that is, how to turn off the timer. The example is given below.
WXML Code
<view class='countDown'>Countdown:<text style='color:red'>{{countDownNum}}</text>s</view>
JS code:
Page({ /** * Initial data of the page */ data: { timer: '',//Timer name countDownNum: '60'//The initial countdown value }, onShow: function(){ //When the countdown is triggered, this function is called wherever it is (); }, countDown: function () { let that = this; let countDownNum = ;//Get the initial countdown value //If the timer is set outside, the user will not see the dynamic change of countDownNum value, so the timer must be stored in data ({ timer: setInterval(function () {// Here we assign setInterval to a variable named timer //Every second countDownNum is reduced by one to achieve synchronization countDownNum--; //Then save countDownNum into data so that the user knows that time is counting down ({ countDownNum: countDownNum }) //When the countdown has not reached 0, you can do other things in the meantime, according to the project requirements if (countDownNum == 0) { //It is important to note here that the timer is always going. If your time is 0, then you have to turn off the timer! Otherwise it will consume performance //Because the timer exists in the data, when it is turned off, it must also be removed from the data before closing it. clearInterval(); //After closing the timer, other processing can be done codes go here } }, 1000) }) } })
OK, this is the simple countdown implementation process. You can copy the code to the WeChat developer tool to verify the effect.
The above is the detailed explanation and integration of the countdown effect of WeChat mini-programs introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!