Przeglądaj źródła

fix: allow invalid time argument for debounce

Gerald 6 lat temu
rodzic
commit
fb51ca4197
2 zmienionych plików z 36 dodań i 5 usunięć
  1. 6 5
      src/common/util.js
  2. 30 0
      test/common/index.test.js

+ 6 - 5
src/common/util.js

@@ -23,6 +23,7 @@ export function debounce(func, time) {
   let startTime;
   let timer;
   let callback;
+  time = Math.max(0, +time || 0);
   function checkTime() {
     timer = null;
     if (performance.now() >= startTime) callback();
@@ -46,13 +47,13 @@ export function debounce(func, time) {
 }
 
 export function throttle(func, time) {
-  let timer;
+  let lastTime = 0;
+  time = Math.max(0, +time || 0);
   function throttledFunction(...args) {
-    if (!timer) {
+    const now = performance.now();
+    if (lastTime + time < now) {
+      lastTime = now;
       func.apply(this, args);
-      timer = setTimeout(() => {
-        timer = null;
-      }, time);
     }
   }
   return throttledFunction;

+ 30 - 0
test/common/index.test.js

@@ -45,6 +45,21 @@ test('debounce', (t) => {
   t.end();
 });
 
+test('debounce with invalid time', (t) => {
+  for (const time of [undefined, -100]) {
+    const log = [];
+    const fn = debounce((i) => {
+      log.push(i);
+    }, time);
+    for (let i = 0; i < 3; i += 1) {
+      fn(i);
+    }
+    mocker.clock.tick(500);
+    t.deepEqual(log, [2]);
+  }
+  t.end();
+});
+
 test('throttle', (t) => {
   const log = [];
   const fn = throttle((i) => {
@@ -62,3 +77,18 @@ test('throttle', (t) => {
   t.deepEqual(log, [0, 3, 0, 1, 2]);
   t.end();
 });
+
+test('throttle with invalid time', (t) => {
+  for (const time of [undefined, -100]) {
+    const log = [];
+    const fn = throttle((i) => {
+      log.push(i);
+    }, time);
+    for (let i = 0; i < 3; i += 1) {
+      fn(i);
+    }
+    mocker.clock.tick(500);
+    t.deepEqual(log, [0]);
+  }
+  t.end();
+});