A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

JS经常会遇到延迟执行的动作,并且失败后自动尝试,尝试N次之后就不再尝试的需求,今天刚好又遇到,于是写个闭包,以后不断完善继续复用。

用法:

// 检查并计数
// 第一个参数用来标记是尝试哪个动作的,第二个参数是最大尝试次数
// 返回 true表示未达到最大值  false表示超过最大值
Counter.check('play', 3); // 执行前3次返回true,第4次返回false,第5次返回true开始新循环...

// 计数器清0,执行成功后清空计数
// 第一个参数是标记
Counter.reset('play');

// 查看计数器值
// 第一个参数是标记
Counter.see('play');
1
2
3
4
5
6
7
8
9
10
11
12
我的使用例子:

function action() {
    // do something or check somthing
    if (success || ready) {
        // 成功后清空计数器
        Counter.reset('play');
        return true;
    }
    // 检查是否重试超过10次
    if (! Counter.check('play', 10)) {
        return false;
    }
    // 500毫秒后继续尝试
    setTimeout(function(){
        action();
    }, 500);
    return false;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
源码:

var Counter = (function () {
    var flagArr = [];
    var count = [];
    var getIndex = function (flag) {
        if (flagArr.indexOf(flag) == -1) {
            flagArr.push(flag);
        }
        return flagArr.indexOf(flag);
    }
    return {
        check: function (flag, max) {
            let index = getIndex(flag)
            if (count[index] == undefined) {
                count[index] = {
                    count: 1,
                }
                return true;
            }
            count[index].count ++;
            if (count[index].count > max) {
                count[index].count = 0;
                return false;
            }
            return true;
        },
        reset: function (flag) {
            count[getIndex(flag)] = {
                count: 0,
            }
        },
        see: function (flag) {
            let index = getIndex(flag);
            return (count[index] == undefined) ? 0 : count[index].count;
        }
    }
})();
---------------------
转载,仅作分享,侵删
作者:sscsdl
原文:https://blog.csdn.net/c513881038/article/details/85551612


1 个回复

倒序浏览
奈斯,加油
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马