Skip to content

Commit

Permalink
📙: fix premature reset on debounce named with immediate
Browse files Browse the repository at this point in the history
  • Loading branch information
merryman committed Aug 1, 2024
1 parent e920616 commit a2889cf
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
5 changes: 3 additions & 2 deletions lively.lang/function.js
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,7 @@ function throttle (func, wait) {
* delay(curry(f, "call3"), 0.15);
* // => Will eventually output: "running after 352ms with arg call3"
*/

function debounce (wait, func, immediate) {
let timeout;
return function () {
Expand Down Expand Up @@ -361,8 +362,8 @@ function debounceNamed (name, wait, func, immediate) {
const store = _debouncedByName;
if (store[name]) return store[name];
function debounceNamedWrapper () {
// ignore-in-doc, cleaning up
delete store[name];
if (!immediate) delete store[name];
else setTimeout(() => delete store[name], wait);
return func.apply(this, arguments);
}
return store[name] = debounce(wait, debounceNamedWrapper, immediate);
Expand Down
18 changes: 17 additions & 1 deletion lively.lang/tests/function-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,28 @@ describe('fun', function () {
var i = setInterval(function () {
if (typeof result === 'undefined') return;
clearInterval(i);
expect(called).to.equal(1, 'debounce call cound');
expect(called).to.equal(1, 'debounce call count');
expect(result).to.equal(10, 'debounce result');
done();
}, 0);
});

it('properly debounces named if immediate execution enabled', async function () {
let called = 0; let result;
fun.debounceNamed('testDebouncedCommandNamed', 20,
function (i) { result = i; called++; }, true)(1);
await promise.delay(10);
fun.debounceNamed('testDebouncedCommandNamed', 20,
function (i) { result = i; called++; }, true)(2);
await promise.delay(10);
fun.debounceNamed('testDebouncedCommandNamed', 20,
function (i) { result = i; called++; }, true)(3);
await promise.delay(20);

expect(called).to.equal(2, 'debounce call count');
expect(result).to.equal(3, 'debounce result');
});

it('throttles calls', function (done) {
let called = 0; let result = [];

Expand Down

0 comments on commit a2889cf

Please sign in to comment.