setTimeout(function() {
console.log('doSomething')
}, 2000);
clearTimeout(timeoutID)
setInterval
与setTimeout
的使用差别不大,参数都是一样的,区别就在于setTimeout
是到时执行一次,setInterval
是根据设置的时间来回调的,比如每秒回调一次。
下面以一个获取验证码
的场景来简单示例下:
业务:点击获取验证码按钮之后开启一个60s的倒计时,并置灰按钮,60s之后恢复可点击状态。
data: {
color: "#ff6f10", //按钮颜色
disabled: false, //是否可以点击
getCode: "获取验证码", //显示文字
},
<button size="mini" type="default" plain="true" class='form-code-btn'
bindtap='sendCode' style='color:{{color}}; border-color: {{color}};background-color:#FFF;'
disabled="{{disabled}}">{{getCode}}</button>
sendCode
sendCode: function(e) {
var that = this;
var times = 0
var i = setInterval(function() {
times++
if (times >= 60) {
that.setData({
color: "#ff6f10",
disabled: false,
getCode: "获取验证码",
})
clearInterval(i)
} else {
that.setData({
getCode: "重新获取" + times + "s",
color: "#999",
disabled: true
})
}
}, 1000)
}
clearInterval(i)
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有