setTimeout()和setInterval(),发送验证码的应用

<template>
  <div>
    <p @click="codeFn" v-if='isShow'>发送验证码</p>
    <p v-else>{{text}}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      text: 6,//倒计时起始时间
      timerId: '',
      intervalId: '',
      isShow: true
    }
  },
  created () {
    this.timeoutFn()// 控制台可以看到延时计时器执行情况
  },
  methods: {
    // 一,延时计时器,(注意是异步,会晚于同步代码执行),延迟一段时间执行,执行一次
    timeoutFn() {
      this.timerId = setTimeout(() => {
        console.log('aa')
      }, 5000)// 5秒以后执行console.log('aa')
      console.log('this.timerId', this.timerId)// this.timerId用来存储setTimeout()的返回值
    },
    // 清除延时计时器-----clearTimeout()
    clearTimeoutFn() {
      clearTimeout(this.timerId)
    },
    // 二,循环计时器-循环执行
    intervalFn() {
      this.intervalId = setInterval(() => {
        if (this.text > 1) { // 现在最后显示的数字是1,如果要最后数字是0,改为this.text > 0
          this.text--
          console.log(this.text)
        } else if (this.text === 1) { // 现在最后显示的数字是1,如果要最后数字是0,改为this.text === 0
          this.isShow = true // 显示'发送验证码'
        }
      }, 1000)
    },
    // 清除循环计时器----clearInterval()
    clearIntervalFn() {
      clearInterval(this.intervalId)
    },
    // 点击发送验证码
    codeFn() {
      this.text = 6
      this.isShow = false // 关闭'发送验证码'
      this.clearIntervalFn() // 先清除循环计时器
      this.intervalFn()// 再调用循环计时器
    }
    // 三,延时计时器,自调用,也可以实现倒计时效果,关键代码-setTimeout(this.timeoutFn, 1000)
    // timeoutFn() {
    //   this.text--
    //   this.timerId = setTimeout(this.timeoutFn, 1000)// this.timeoutFn自调用
    //   if (this.text < 1) {
    //     clearTimeout(this.timerId)// 清除定时器
    //     this.isShow = true // 显示'发送验证码'
    //   }
    // }
  }
      intervalFn2() {
      this.intervalId = setInterval(() => {
        if (this.text > 1) { // 现在最后显示的数字是1,如果要最后数字是0,改为this.text > 0
          this.text--
          console.log(this.text)
        } else if (this.text === 1) { // 现在最后显示的数字是1,如果要最后数字是0,改为this.text === 0
          this.isShow = true // 显示'发送验证码'
          console.log('1231111')
          clearInterval(this.intervalId)// 清除循环计时器
        }
      }, 1000)
    }

}
</script>

<style>

</style>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值