资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

javascript中统计函数执行次数的方法是什么

这篇文章主要介绍javascript中统计函数执行次数的方法是什么,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

创新互联主要企业基础官网建设,电商平台建设,移动手机平台,重庆小程序开发等一系列专为中小企业定制开发产品体系;应对中小企业在互联网运营的各种问题,为中小企业在互联网的运营中保驾护航。

一、统计函数执行次数

常规的方法可以使用 console.log 输出来肉眼计算有多少个输出

不过在Chrome中内置了一个 console.count 方法,可以统计一个字符串输出的次数。我们可以利用这个来间接地统计函数的执行次数

function someFunction() {
 console.count('some 已经执行');
}
function otherFunction() {
 console.count('other 已经执行');
}
someFunction(); // some 已经执行: 1
someFunction(); // some 已经执行: 2
otherFunction(); // other 已经执行: 1
console.count(); // default: 1
console.count(); // default: 2

不带参数则为 default 值,否则将会输出该字符串的执行次数,观测起来还是挺方便的

当然,除了输出次数之外,还想获取一个纯粹的次数值,可以用装饰器将函数包装一下,内部使用对象存储调用次数即可

var getFunCallTimes = (function() {
 
 // 装饰器,在当前函数执行前先执行另一个函数
 function decoratorBefore(fn, beforeFn) {
 return function() {
 var ret = beforeFn.apply(this, arguments);
 // 在前一个函数中判断,不需要执行当前函数
 if (ret !== false) {
 fn.apply(this, arguments);
 }
 };
 }
 
 // 执行次数
 var funTimes = {};
 
 // 给fun添加装饰器,fun执行前将进行计数累加
 return function(fun, funName) {
 // 存储的key值
 funName = funName || fun;
 
 // 不重复绑定,有则返回
 if (funTimes[funName]) {
 return funTimes[funName];
 }
 
 // 绑定
 funTimes[funName] = decoratorBefore(fun, function() {
 // 计数累加
 funTimes[funName].callTimes++;
 console.log('count', funTimes[funName].callTimes);
 });
 
 // 定义函数的值为计数值(初始化)
 funTimes[funName].callTimes = 0;
 return funTimes[funName];
 }
})();

function someFunction() {
 
}
function otherFunction() {
 
}
someFunction = getFunCallTimes(someFunction, 'someFunction');
someFunction(); // count 1
someFunction(); // count 2
someFunction(); // count 3
someFunction(); // count 4
console.log(someFunction.callTimes); // 4
otherFunction = getFunCallTimes(otherFunction);
otherFunction(); // count 1
console.log(otherFunction.callTimes); // 1
otherFunction(); // count 2
console.log(otherFunction.callTimes); // 2

如何控制函数的调用次数

也可以通过闭包来控制函数的执行次数

function someFunction() {
 console.log(1);
}
function otherFunction() {
 console.log(2);
}
function setFunCallMaxTimes(fun, times, nextFun) {
 return function() {
 if (times-- > 0) {
 // 执行函数
 return fun.apply(this, arguments);
 } else if (nextFun && typeof nextFun === 'function') {
 // 执行下一个函数
 return nextFun.apply(this, arguments);
 }
 };
}
var fun = setFunCallMaxTimes(someFunction, 3, otherFunction);
fun(); // 1
fun(); // 1
fun(); // 1
fun(); // 2
fun(); // 2

以上是javascript中统计函数执行次数的方法是什么的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注创新互联行业资讯频道!


分享标题:javascript中统计函数执行次数的方法是什么
转载注明:http://cdkjz.cn/article/ghcjjj.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220