微信小程序 写一个获取验证码 及setInterval 使用基本方法
<!--index.wxml--> <view class="container"> <view class="container_content"> <view class="content_time">{{time}}S</view> <view class="content_btn"> <button class="btn_start" bindtap="startTap">开始</button> <button class="btn_stop" bindtap="stopTap">停止</button> <button class="btn_restart" bindtap="restartTap">重新开始</button> </view> </view> </view>
/**index.wxss**/ .container { height: 100%; width: 100%; padding: 0; margin: 0; } .container_content { height: 100%; width: 100%; margin-top:40%; text-align: center; } .content_time { color: forestgreen; font-size: 50rpx; } .btn_start { width: 30%; text-align: center; background-color: green; } .btn_stop { width: 30%; text-align: center; background-color: red; } .btn_restart { width: 30%; text-align: center; background-color: darkcyan; }
//index.js Page({ data: { time: 60, //初始时间 interval: "" //定时器 }, /** * 开始倒计时 */ startTap:function () { var that = this; that.init(that); //这步很重要,没有这步,重复点击会出现多个定时器 var time = that.data.time; console.log("倒计时开始") var interval = setInterval(function () { time--; that.setData({ time: time }) if (time==0){ //归0时回到60 that.restartTap(); } },100) that.setData({ interval:interval }) }, /** * 暂停倒计时 */ stopTap:function () { var that = this; console.log("倒计时暂停") that.clearTimeInterval(that) }, /** * 重新倒计时 */ restartTap:function () { var that = this; that.init(that); console.log("倒计时重新开始") that.startTap() }, /** * 初始化数据 */ init: function (that) { var time = 60; var interval = "" that.clearTimeInterval(that) that.setData({ time: time, interval: interval, }) }, /** * 清除interval * @param that */ clearTimeInterval: function (that) { var interval = that.data.interval; clearInterval(interval) }, /** * 生命周期函数--监听页面卸载 * 退出本页面时停止计时器 */ onUnload:function () { var that = this; that.clearTimeInterval(that) }, /** * 生命周期函数--监听页面隐藏 * 在后台运行时停止计时器 */ onHide:function () { var that = this; that.clearTimeInterval(that) } })
---------------------
作者:平凡V之路
来源:CSDN
原文:https://blog.csdn.net/qq_36221503/article/details/79732381
版权声明:本文为博主原创文章,转载请附上博文链接!