在JS中統計函式執行次數
阿新 • • 發佈:2018-12-17
一、統計函式執行次數
常規的方法可以使用 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