From c997759c1be6e895e9b26af740c42744a777675f Mon Sep 17 00:00:00 2001 From: Aaron Beall Date: Wed, 15 Nov 2023 07:28:25 -0500 Subject: [PATCH] Fix recursive callback args (#32) --- .gitignore | 1 + index.js | 6 ++++-- test.js | 20 ++++++++++++++++++++ 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index 48a2e24..aa6fd7c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ components build +node_modules \ No newline at end of file diff --git a/index.js b/index.js index c6a22c1..a2b4947 100644 --- a/index.js +++ b/index.js @@ -24,8 +24,9 @@ function debounce(func, wait, immediate){ } else { timeout = null; if (!immediate) { - result = func.apply(context, args); + var callContext = context, callArgs = args context = args = null; + result = func.apply(callContext, callArgs); } } }; @@ -37,8 +38,9 @@ function debounce(func, wait, immediate){ var callNow = immediate && !timeout; if (!timeout) timeout = setTimeout(later, wait); if (callNow) { - result = func.apply(context, args); + var callContext = context, callArgs = args context = args = null; + result = func.apply(callContext, callArgs); } return result; diff --git a/test.js b/test.js index f2890e8..be0d95a 100644 --- a/test.js +++ b/test.js @@ -167,4 +167,24 @@ describe('forcing execution', function() { }) + it('should execute with correct args when called again from within timeout', function() { + const callback = sinon.spy(n => + // recursively call debounced function until n == 0 + --n && fn(n) + ); + + const fn = debounce(callback, 100) + + fn(3) + + clock.tick(125) + clock.tick(250) + clock.tick(375) + + expect(callback.callCount).toEqual(3) + expect(callback.args[0]).toEqual([3]) + expect(callback.args[1]).toEqual([2]) + expect(callback.args[2]).toEqual([1]) + }); + })