Interview Question

Front End Engineer Interview

-Waterloo, ON

Facebook

Related to question 1, how could you implement debouncing? Say you wanted the `handleScroll` function to be called only after 200ms has passed between scroll events.

Answer

Interview Answers

4 Answers

1

A good example can be read here: http://davidwalsh.name/javascript-debounce-function

Anonymous on

1

const debounce = (callback, time) => { let timeout = null; return () => { clearTimeout(timeout); timeout = setTimeout[() => { callback(); }, time); } } const logger = (e) => { console.log('server called with'); } window.addEventListener('scroll', debounce(logger, 400));

ela pou sai on

0

You should use keep track of the time at which the previous scroll was called. var recentScrollTime = 0; var currentScrollEvt = undefined; delayedHandleScroll(Date.now()) delayedHandleScroll = (timeCalled) => { RecentScrollTime = timeCalled; if (timeCalled - recentScrollTime > 200) { ClearTimeout(currentScrollEvt) // check if currentScroll isn’t undefined first though handleScrollFn() } else { if (currentScrollEvent) { ClearTimeout(currentScrollEvt); } // Set the scroll event to fired after the 200ms // this solves the case when the next scroll was called less than 200ms after without dismissing it completely currentScrollEvt = setTimeout[handleScrollFn, timeCalled-recentScrollTime) } }

Anonymous on

2

(function waitHandleScroll(){ handleScroll(); setTimeout[waitHandleScroll, 200); })();

Osvaldo on

One or more comments have been removed.
Please see our Community Guidelines or Terms of Service for more information.

Add Answers or Comments

To comment on this, Sign In or Sign Up.