微信小程序发送短信倒计时代码

test.wxml

<button size="mini" disabled="{{send_disabled}}" bindtap="sendSMSCode">{{send_text}}</button>

test.js

Page({
  data: {
    send_text: '发送',
    send_disabled: false,
    send_time: null
  },
  onLoad: function (options) {
  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  sendSMSCode: function () {
    this.setData({
      send_disabled: true
    })
    var that = this
    wx.request({
      url: 'this is your send sms sode url',
      data: {},
      method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      // header: {}, // 设置请求的 header
      success: function (res) {
        // success
        // 开始倒计时
        that.setData({
          send_time: Math.round(+new Date() / 1000)
        })
        that.sendCountDown()
      },
      fail: function () {
        // fail
        that.setData({
          send_disabled: false
        })
      },
      complete: function () {
        // complete
      }
    })
  },
  sendCountDown: function () {
    if (!this.data.send_time) {
      return
    }
    var seconds = this.data.send_time + 60 - Math.round(+new Date() / 1000)
    if (seconds > 0) {
      this.setData({
        send_text: `(${seconds}s)`
      })
      setTimeout(this.sendCountDown, 1000)
    } else {
      this.setData({
        send_text: '发送',
        send_disabled: false,
        send_time: null
      })
    }
  }
})
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容