Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add simpler solution #20

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all 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
28 changes: 5 additions & 23 deletions coding-harder/debounce.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,11 @@
/// solution

function debounce(fn, delay = 0) {

// keep track of the last call to the debounced function
let last = {
time: null,
timerId: null
}

// return a debounced version of fn
return () => {
let time = Date.now()

// if the debounced function was called again before the delay elapsed,
// cancel the timer (started in the previous call) that would have called
// fn, and start a new timer.
if (last.time && (time - last.time) < delay) {
clearTimeout(last.timerId)
}

// start a timer to call fn after the given delay
last = {
time,
timerId: setTimeout(fn, delay)
}
let timer;

return function() {
if (timer) clearTimeout(timer);
timer = setTimeout(fn, delay);
}
}

Expand Down