微信小程序setInterval定时函数使用详细教程

1、setInterval的理解
(1)setInterval理解
setInterval定时函数,就是延迟多长时间不停的调用 setInterval中的函数,想具体了解 setInterval函数,我们先看一下 setInterval函数组成部分。
(2)setInterval组成
setInterval(function () {},时间)。function () {}就是不停执行函数,时间就是延迟多久不断地执行,重点function () {}函数
具体示例:

 setInterval(function () {
 				//.toClock1()是具体函数,写在外边
 				_this.toClock1();}, 6000);

(3)setInterval需要关闭
使用clearInterval()去关闭,具体使用看下面的内容

clearInterval()

2、setInterval放在微信小程序onshow函数里
onShow:页面显示或从后台跳回小程序时显示此页面时触发,从跳转页面返回时触发,不能传递参数
3、setInterval具体使用
(1)设置全局变量timer(timer随便起)

//在微信小程序data中写如下代码,timer全局变量
 data: {
    timer: null,
  },

(2)onshow写setInterval函数

onShow: function () {
      const
  • 9
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一个简单的微信小程序番茄时钟的代码示例: 1. 在 `app.json` 文件中添加页面路径: ```json { "pages": [ "pages/tomato/tomato" ] } ``` 2. 在 `pages` 目录下创建 `tomato` 目录,并在其中添加 `tomato.wxml`、`tomato.wxss`、`tomato.js` 和 `tomato.json` 文件。 3. 在 `tomato.wxml` 文件中添加以下代码: ```html <view class="container"> <view class="timer">{{time}}</view> <view class="buttons"> <button class="start" bindtap="start">开始</button> <button class="stop" bindtap="stop">停止</button> </view> </view> ``` 4. 在 `tomato.wxss` 文件中添加以下代码: ```css .container { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; } .timer { font-size: 48px; font-weight: bold; margin-bottom: 24px; } .buttons { display: flex; } button { margin: 0 16px; } ``` 5. 在 `tomato.js` 文件中添加以下代码: ```javascript const TIMER_DURATION = 25 * 60 * 1000; // 25 minutes in milliseconds Page({ data: { time: '25:00', timer: null, remainingTime: TIMER_DURATION }, start() { if (this.data.timer) { return; } this.data.timer = setInterval(() => { if (this.data.remainingTime <= 0) { clearInterval(this.data.timer); this.data.timer = null; wx.showToast({ title: '番茄时间结束!', icon: 'none' }); return; } const minutes = Math.floor(this.data.remainingTime / 60000); const seconds = Math.floor((this.data.remainingTime % 60000) / 1000); this.setData({ time: `${minutes < 10 ? '0' + minutes : minutes}:${seconds < 10 ? '0' + seconds : seconds}`, remainingTime: this.data.remainingTime - 1000 }); }, 1000); }, stop() { if (this.data.timer) { clearInterval(this.data.timer); this.data.timer = null; } } }); ``` 6. 在 `tomato.json` 文件中添加以下代码: ```json { "navigationBarTitleText": "番茄时钟" } ``` 这样就完成了一个简单的微信小程序番茄时钟的实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

1029179954

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值