setInterval如何实现暂停效果?

ppylox
·5/31/2021·0 阅读
AI 摘要模型根据正文自动生成,仅供参考

setInterval实现暂停效果的核心是分离定时器与累计秒数:用变量保存总秒数和定时器实例,每秒累加秒数;暂停时仅clearInterval而不清空秒数,继续时新开定时器并基于原秒数累加;重置则同时清空定时器和秒数。文中给出Vue示例,包含startTimer、puseTimer(暂停)、clearTimer(重置)方法,并按分钟取模触发通知提示。

setInterval 实现暂停效果的思路:

1、用一个变量保存总秒数,用一个变量保存当前的setInterval

2、每过一秒钟都更新到总秒数的变量里面

3、点击暂停按钮,清空当前setInterval,但是不清空总秒数

4、点击继续,则新开一个计时,继续累加之前的秒数

5、如果要重头开始,则需要清空当前setInterval并且清空当前秒数。

以下为vue中的demo:

data() {\n    return {\n      setIntervalData: null,\n      currSeconds: 0\n    };\n  },\n  mounted() {\n    // 开始计时\n    this.startTimer();\n  },\n  methods: {\n    showTimer(currSeconds) {\n      var currMinutes = currSeconds/60\n       // 每一秒钟提示一次,具体几秒钟可自定义,如果需要每五分钟提示一次,就currMinutes % 5 === 0\n      if (currMinutes % 1 === 0) {\n        console.log(`已汇报${currMinutes}分钟`)\n        this.$notify({\n        title: "",\n        message: `已汇报${currMinutes}分钟`,\n        position: "bottom-right",\n        duration: 0,\n        customClass: 'countdown-timer'\n      });\n      }\n    },\n    startTimer() {\n    // 开始新的计时,不管暂停还是重新开始都新开一个setInterval,并且累加秒\n      this.setIntervalData = setInterval(() => {\n        this.currSeconds += 1;\n        this.showTimer(this.currSeconds);\n      }, 1000);\n    },\n    /**\n     * 清空定时器且清空总秒数\n     */\n    clearTimer() {\n      clearInterval(this.setIntervalData)\n      this.currSeconds = 0\n    },\n    /**\n     * 暂时定时器:需清空定时器,但不清除已统计总时长,方便在暂停后重启定时器\n     */\n    puseTimer() {\n      clearInterval(this.setIntervalData)\n    }\n


相关文章

评论 (0)

暂无评论,来写第一条吧