Skip to content
This repository has been archived by the owner on Jul 30, 2018. It is now read-only.

Guarantee util.throttle delay #360

Merged
merged 3 commits into from
Nov 3, 2017
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 28 additions & 5 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,15 @@ export function createTimer(callback: (...args: any[]) => void, delay?: number):
export function debounce<T extends (this: any, ...args: any[]) => void>(callback: T, delay: number): T {
// node.d.ts clobbers setTimeout/clearTimeout with versions that return/receive NodeJS.Timer,
// but browsers return/receive a number
let timer: any;
let timer: Handle | null;

return <T> function () {
timer && clearTimeout(timer);
timer && timer.destroy();

let context = this;
let args: IArguments | null = arguments;

timer = setTimeout(function () {
timer = guaranteeMinimumTimeout(function () {
callback.apply(context, args);
args = context = timer = null;
}, delay);
Expand All @@ -62,7 +62,7 @@ export function throttle<T extends (this: any, ...args: any[]) => void>(callback
ran = true;

callback.apply(this, arguments);
setTimeout(function () {
guaranteeMinimumTimeout(function () {
ran = null;
}, delay);
};
Expand All @@ -89,9 +89,32 @@ export function throttleAfter<T extends (this: any, ...args: any[]) => void>(cal
let context = this;
let args: IArguments | null = arguments;

setTimeout(function () {
guaranteeMinimumTimeout(function () {
callback.apply(context, args);
args = context = ran = null;
}, delay);
};
}

export function guaranteeMinimumTimeout(callback: (...args: any[]) => void, delay?: number): Handle {
const startTime = Date.now();
let timerId: number | null;

function timeoutHandler() {
const delta = Date.now() - startTime;
if (delay == null || delta >= delay) {
callback();
} else {
// Cast setTimeout return value to fix TypeScript parsing bug. Without it,
// it thinks we are using the Node version of setTimeout.
timerId = <any> setTimeout(timeoutHandler, delta);
Copy link
Contributor

@maier49 maier49 Nov 3, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we be timing out for delay - delta? What we're saying here is that we want to wait as long as we've waited right? That seems arbitrary

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixing now...

}
}
timerId = setTimeout(timeoutHandler, delay);
return createHandle(() => {
if (timerId != null) {
clearTimeout(timerId);
timerId = null;
}
});
}
Loading