微信小程序setInterval定時函數(shù)新手使用的超詳細教程
1、setInterval的理解
(1)setInterval理解
setInterval定時函數(shù),就是延遲多長時間不停的調用 setInterval中的函數(shù),想具體了解 setInterval函數(shù),我們先看一下 setInterval函數(shù)組成部分。
(2)setInterval組成
setInterval(function () {},時間)。function () {}就是不停執(zhí)行函數(shù),時間就是延遲多久不斷地執(zhí)行,重點function () {}函數(shù)
具體示例:
setInterval(function () {
//.toClock1()是具體函數(shù),寫在外邊
_this.toClock1();}, 6000);
(3)setInterval需要關閉
使用clearInterval()去關閉,具體使用看下面的內容
clearInterval()
2、setInterval放在微信小程序onshow函數(shù)里
onShow:頁面顯示或從后臺跳回小程序時顯示此頁面時觸發(fā),從跳轉頁面返回時觸發(fā),不能傳遞參數(shù)
3、setInterval具體使用
(1)設置全局變量timer(timer隨便起)
//在微信小程序data中寫如下代碼,timer全局變量
data: {
timer: null,
},
(2)onshow寫setInterval函數(shù)
onShow: function () {
? ? ? const _this = this
? ? ? ?//定時器 ?函數(shù)賦值給timer ?方便clearInterval()使用
? ? ? ?_this.data.timer = setInterval(
? ? ? ? ?function () {
? ? ? ? _this.toClock1(); ? ? ? ?
? ? ? ? }, 6000);
?? ? ? ?_this.setData({
?? ? ? ? ?timer:_this.data.timer
?? ? ? ?});
? },toClock1()函數(shù)
//定時函數(shù)執(zhí)行的內容 自己發(fā)揮 寫自己的代碼
toClock1(){
console.log(this.data.timer)
}
4、離開當前頁面關閉 setInterval定時函數(shù)
代碼放在onhide里邊
onHide: function () {
//關閉clearInterval定時函數(shù)
clearInterval(this.data.timer);
this.setData({
timer: null
});
console.log(this.data.timer)
},
附:微信小程序定時器setInterval()的使用注意事項
setInterval(function(){}, number 時間間隔/ms)
注意在setInterval中定義的函數(shù)中使用 this 指向的是該計時器,若要用到頁面數(shù)據(jù)應如下操作:
let that=this
setInterval(function(){
? ?that.data.a=0;
},number 時間間隔/ms)通過在setInterval外面設置一個變量 that 獲得 頁面 this 的引用,后進行操作
總結
到此這篇關于微信小程序setInterval定時函數(shù)使用的文章就介紹到這了,更多相關微信小程序setInterval定時函數(shù)內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
解決layui動態(tài)添加的元素click等事件觸發(fā)不了的問題
今天小編就為大家分享一篇解決layui動態(tài)添加的元素click等事件觸發(fā)不了的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-09-09
Bootstrap彈出框(modal)垂直居中的問題及解決方案詳解
這篇文章主要介紹了Bootstrap彈出框(modal)垂直居中的問題及解決方案詳解的相關資料,非常不錯具有參考借鑒價值,需要的朋友可以參考下2016-06-06
Chrome中模態(tài)對話框showModalDialog返回值問題的解決方法
chrome中彈出模態(tài)對話框,通過window.returnValue賦返回值關閉后,有的情況下無法取得返回值。2010-05-05
javascript動態(tài)添加表格數(shù)據(jù)行(ASP后臺數(shù)據(jù)庫保存例子)
本文,我將以一個類似的例子來做一個前臺用Javascript動態(tài)添加數(shù)據(jù)項,后臺保存到數(shù)據(jù)庫的例子。2010-05-05

