在JS中統計函數執行次數

1、統計函數執行次數bash

常規的方法能夠使用 console.log 輸出來肉眼計算有多少個輸出閉包

不過在Chrome中內置了一個 console.count 方法,能夠統計一個字符串輸出的次數。咱們能夠利用這個來間接地統計函數的執行次數app

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 值,不然將會輸出該字符串的執行次數,觀測起來仍是挺方便的函數

固然,除了輸出次數以外,還想獲取一個純粹的次數值,能夠用裝飾器將函數包裝一下,內部使用對象存儲調用次數便可ui

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
複製代碼

如何控制函數的調用次數this

也能夠經過閉包來控制函數的執行次數spa

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
複製代碼

全棧開發交流羣:864305860.png
相關文章
相關標籤/搜索