JavaScript循环计数器

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

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

我的使用例子:

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;
}

有想要学习Web前端的小伙伴,小编在这推荐下自己的Web学习群:585843909,群内不定期分享干货,进群就可领取基础教学视频,欢迎各位加入

源码:

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;
 }
 }
})();

有想要学习Web前端的小伙伴,小编在这推荐下自己的Web学习群:585843909,群内不定期分享干货,进群就可领取基础教学视频,欢迎各位加入

原文:https://blog.csdn.net/c513881038/article/details/85551612

猜你喜欢

转载自blog.csdn.net/weixin_44297376/article/details/85623612