JavaScript

Prevent Over-frequent Code

On resize, or on scroll… To avoid over-calculating:


e.g., on scroll:

timer = null

$(document).on 'scroll', () =>
  t = Date.now()

  setTimeout =>
    return if t - timer < 100 # interval of getting scrollY

    # do some expensive stuff
    # won't be more frequent than once every 100ms
        
    timer = t
  , 150 # after 150ms of the last scroll, fire the code above
Standard