在JS中統計函數執行次數

一、統計函數執行次數

常規的方法可以使用 console.log 輸出來肉眼計算有多少個輸出

在JS中統計函數執行次數

不過在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

對前端的技術,架構技術感興趣的同學關注我的頭條號,並在後臺私信發送關鍵字:“前端”即可獲取免費的架構師學習資料

知識體系已整理好,歡迎免費領取。還有面試視頻分享可以免費獲取。關注我,可以獲得沒有的經驗哦!


分享到:


相關文章: