Skip to content

Commit

Permalink
Fix recursive callback args (#32)
Browse files Browse the repository at this point in the history
  • Loading branch information
aaronbeall committed Nov 15, 2023
1 parent 991d8fe commit c997759
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
1 change: 1 addition & 0 deletions .gitignore
@@ -1,2 +1,3 @@
components
build
node_modules
6 changes: 4 additions & 2 deletions index.js
Expand Up @@ -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);
}
}
};
Expand All @@ -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;
Expand Down
20 changes: 20 additions & 0 deletions test.js
Expand Up @@ -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])
});

})

0 comments on commit c997759

Please sign in to comment.