Bladeren bron

以节流方式纪录当前系统模式的日志

dengdx 1 maand geleden
bovenliggende
commit
e972052df3
2 gewijzigde bestanden met toevoegingen van 24 en 1 verwijderingen
  1. 7 1
      src/API/interceptor.ts
  2. 17 0
      src/utils/throttle.ts

+ 7 - 1
src/API/interceptor.ts

@@ -3,15 +3,21 @@ import store from '../states/store';
 import { API_BASE_URL } from './config';
 import { SystemMode } from '../states/systemModeSlice';
 import emitter from '../utils/eventEmitter';
+import { throttleCount } from '@/utils/throttle';
 
 const axiosInstance = axios.create({
   baseURL: API_BASE_URL,
 });
 
+function expensiveLog(mode) {
+  console.log(`当前系统模式:${mode}`);
+}
+const log = throttleCount(expensiveLog, 60);
+
 axiosInstance.interceptors.request.use(
   (config) => {
     const state = store.getState();
-    console.log(`当前系统模式:${state.systemMode.mode}`);
+    log(state.systemMode.mode);
 
     const token =
       state.systemMode.mode === SystemMode.Emergency

+ 17 - 0
src/utils/throttle.ts

@@ -0,0 +1,17 @@
+/**
+ * 按调用次数做节流
+ * @param {Function} fn     真正要执行的函数
+ * @param {number}   count  每累计调用 count 次才执行 1 次
+ * @returns {Function}      包装后的节流函数
+ */
+export function throttleCount(fn, count) {
+  if (count <= 0) throw new RangeError('count must > 0');
+  let counter = 0;
+  return function (...args) {
+    counter += 1;
+    if (counter >= count) {
+      counter = 0;
+      return fn.apply(this, args);
+    }
+  };
+}