In 2011, an issue popped up on Twitter's feed: when you scrolled down twitter's feed it became really slow and unresponsive. | Shreya

editor-img
Shreya
Oct 1, 2022

In 2011, an issue popped up on Twitter's feed: when you scrolled down twitter's feed it became really slow and unresponsive.

Here's why...

It’s a very, very, bad idea to attach handlers to the window scroll event.

Why?

When you scroll through a trackpad, scrolling wheel, or drag the scrollbar, easily around 30 events per second are triggered. Moreover, when you slowly scroll on a smartphone, easily around 100 events per second are triggered.

These days there are slightly more sophisticated ways of handling events. Let me introduce you to Debounce and Throttle.

Debounce

The debounce technique allows us to “group” multiple raised sequential functions into a single function.

media

Suppose you create a search bar and users can search using keywords in the search bar, and once the user is done you need to show suggestions.

If we tie the search API to the keystroke event, every time a keystroke happens API will be called leading to slow and unreliable performance.

With debounce,

the API will be called after Xms(in the about example 400ms) when the user stops keystrokes leading to a much faster and more reliable user experience.

Usecases:

  • Autocomplete (search)
  • Resize event handler
  • Autosave feature (drafts on fifo.im)
  • Prevent function call on drag and drop

Throttling

By using throttling, we don’t allow our function to execute more than once every X milliseconds.

media

The main difference between this and debouncing is that throttle guarantees the execution of the function regularly, at least every X milliseconds.

Usecase:

  • Scroll event handling in content loading webpages like Twitter
  • Button click handler to prevent spam
  • Mouse move/ touch move event handling
  • Gaming- on keystroke