当前位置:   article > 正文

uni-app - javaScript - vue2 计时器(倒计时和正计时)_uniapp计时器

uniapp计时器

正计时 

1.在data里面定义

  1. data() {
  2. return {
  3. time: '00:00:00',
  4. timer: '',
  5. hour: 0,
  6. minutes: 0,
  7. seconds: 0
  8. }
  9. },

2.页面按钮

  1. <template>
  2. <view>
  3. <button @click="begin">开始计时{{time}}</button>
  4. <button @click="pause">暂停</button>
  5. </view>
  6. </template>

3.开始计时

  1. // 开始计时
  2. begin() {
  3. this.timer = setInterval(this.startTimer, 1000);
  4. },
  5. startTimer() {
  6. this.seconds += 1;
  7. if (this.seconds >= 60) {
  8. this.seconds = 0;
  9. this.minutes = this.minutes + 1;
  10. }
  11. if (this.minutes >= 60) {
  12. this.minutes = 0;
  13. this.hour = this.hour + 1;
  14. }
  15. this.time = (this.hour < 10 ? '0' + this.hour : this.hour) + ':' + (this.minutes < 10 ? '0' + this
  16. .minutes :
  17. this.minutes) + ':' + (this.seconds < 10 ? '0' + this.seconds : this.seconds);
  18. },

4.暂停计时

  1. //暂停计时
  2. pause() {
  3. if (this.timer) {
  4. clearInterval(this.timer);
  5. }
  6. },

倒计时

1.在data里面定义

  1. data() {
  2. return {
  3. timer: '',
  4. examtime: 1000, //
  5. }
  6. },

2.页面显示

  1. <template>
  2. <view>
  3. 倒计时:{{examtime}}
  4. </view>
  5. </template>

3.调用及方法编写

  1. onLoad() {
  2. this.timer = setInterval(this.countDown, 1000) //毫秒 1秒
  3. },
  4. methods: {
  5. //倒计时
  6. countDown() {
  7. var a = this.examtime--
  8. if (a == 0) {
  9. this.examtime = 0
  10. clearInterval(this.timer)
  11. this.show = true
  12. }
  13. },
  14. }

离开页面记得清除定时器

  1. destroyed() {
  2. clearInterval(this.timer);
  3. },

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/671904
推荐阅读