【轉】微信小程序 設置計時器(setInterval)、清除計時器(clearInterval)


原文地址:https://www.cnblogs.com/i-douya/p/8807454.html

1、wxml代碼

<!--index.wxml-->
<view class="container">
  <button type='primary' style='margin-bottom:40px;' bindtap='startSetInter'>開始</button>
  <button type='primary' bindtap='endSetInter'>結束</button>
</view>

2、js代碼

  將計時器賦值給 data 中的變量,這樣在任何方法中都可以清除計時器

Page({
  data: {
      //存儲計時器
    setInter:'',
    num:1,
  },
  onLoad: function () {
      var that = this;       
  },
  startSetInter: function(){
      var that = this;
      //將計時器賦值給setInter
      that.data.setInter = setInterval(
          function () {
              var numVal = that.data.num + 1;
              that.setData({ num: numVal });
              console.log('setInterval==' + that.data.num);
          }
    , 2000);   
  },
  endSetInter: function(){
      var that = this;
      //清除計時器  即清除setInter
      clearInterval(that.data.setInter)
  },
  onHide: function () { 
  },
  onUnload: function () {
      var that =this;
      //清除計時器  即清除setInter
      clearInterval(that.data.setInter)
  }, 
})

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM