這篇文章主要介紹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中統計函數執行次數的方法是什么的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。