React Native 广告,验证码倒计时工具类

因为以前直接用定时器setInterval,每次退出程序的时候,定时器一直不走,这个工具类简单的解决程序退出后台,定时器不走的bug,那么,直接上代码咯~~

/**
 *  Created by zhuang.haipeng on 2017.9.11
 *
 *  广告倒计时,验证码倒计时工具类
 *
 *  用法: //60 * 1000 为60秒 , 60 * 60 * 100 为60分钟 ...
 *  let countdownDate = new Date(new Date().getTime() + 60 * 1000)
 *   CountdownUtil.settimer(countdownDate, (time) => {
 *      Console.log(time) --> {years: 0, days: 0, hours: 0, min: 0, sec: 49, millisec: 0}
 *   }
 *
 *   切记: 在应用工具类的页面退出的时候, 调用CountdownUtil.stop() 清除定时器,以免内存爆了
 */

export default class CountdownUtil {

    /**  定时器 */
    interval = null;

    /**
     *  创建定时器
     *
     */
    static settimer(countdownDate, callbak) {
        this.interval = setInterval(() => {
            let time = this.getDateData(countdownDate)
            callbak && callbak(time)
        }, 1000)
    }


    /**
     * 侄计时计算 -->  通过此方法计算,可以解决应用退出后台的时候,定时器不走
     * @param countdownDate
     * @return {*}
     */
    static getDateData(countdownDate) {
        let diff = (Date.parse(new Date(countdownDate)) - Date.parse(new Date)) / 1000;

        if (diff <= 0) {
         this.stop() // 倒计时为0的时候, 将计时器清除
            return 0;
        }

        const timeLeft = {
            years: 0,
            days: 0,
            hours: 0,
            min: 0,
            sec: 0,
            millisec: 0,
        };

        if (diff >= (365.25 * 86400)) {
            timeLeft.years = Math.floor(diff / (365.25 * 86400));
            diff -= timeLeft.years * 365.25 * 86400;
        }
        if (diff >= 86400) {
            timeLeft.days = Math.floor(diff / 86400);
            diff -= timeLeft.days * 86400;
        }
        if (diff >= 3600) {
            timeLeft.hours = Math.floor(diff / 3600);
            diff -= timeLeft.hours * 3600;
        }
        if (diff >= 60) {
            timeLeft.min = Math.floor(diff / 60);
            diff -= timeLeft.min * 60;
        }
        timeLeft.sec = diff;
        return timeLeft;
    }

    /**
     * 数字补零 --> 例: 00时01分59秒
     * @param num
     * @param length
     * @return {*}
     */
    static leadingZeros(num, length = null) {

        let length_ = length;
        let num_ = num;
        if (length_ === null) {
            length_ = 2;
        }
        num_ = String(num_);
        while (num_.length < length_) {
            num_ = '0' + num_;
        }
        return num_;
    }

    /** 清除定时器 */
    static stop() {
        clearInterval(this.interval);
    }
};

利用callback将转换的时间倒计时传递出去, 您可以打印一下callbak回去的time对象

这里简单以验证码倒计时为例:
思路:
1. 先设置状态机isSentVerify默认true可以发送验证码
2. 点击之后就重新设置状态机isSentVerify为false, 不让用户再次点击发送网络请求
3. 声明倒计时的时间(这里只能在你点击的时候才能声明,如果再componentDidMount中,会一进入就开始计时的)
4. 请求成功后设置倒计时,判断如果time.sec > 0 的时候,则设置时间,否则将文字设置为为“重新获取”
5. 然后判断文字为“重新获取”, 然后将状态机isSentVerify设为true, 这样用户倒计时结束后,可以再次发送验证码。
6. 网络请求失败的时候,在catch处将isSentVerify设置为true,这样用户可以再次获取验证码

 if (this.state.isSentVerify === true) {
            // 倒计时时间
            let countdownDate = new Date(new Date().getTime() + 60 * 1000)
            // 点击之后验证码不能发送网络请求
            this.setState({
                isSentVerify: false
            });

            Api.userRegisterCheckCode(this.state.phoneText)
                .then(
                    (data) => { // 倒计时时间
                        CountdownUtil.settimer(countdownDate, (time) => {
                            this.setState({
                                timerTitle: time.sec > 0 ? time.sec + 's' : '重新获取'
                            }, () => {
                                if (this.state.timerTitle == "重新获取") {
                                    this.setState({
                                        isSentVerify: true
                                    })
                                }
                            })
                        })
                    }
                ).catch((err) => {
                this.setState({
                    isSentVerify: true,
                })
            });
        }

退出页面的时候,记得销毁定时器

  componentWillUnmount() {
        CountdownUtil.stop()
    }

这里写图片描述 这里写图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值