1

I have some heavy function attached to scroll event in my application. To limit frequency of it execution I'm using simple debounce method like this:

var timeout;
document.addEventListener("scroll", function () {
    clearTimeout(timeout);
    timeout = setTimeout(function () {
        // some heavy code
    }, 200);
});

Is there a better way to do this? Isn't setTimeout too heavy itself to call each time the event fires?

EDIT: what concerns me most is memory usage - i think each setTimeout is allocating some. This is memory allocation from chrome timeline (from this fiddle: http://jsfiddle.net/hky0oekm/):

enter image description here

Bodzio
  • 2,440
  • 2
  • 19
  • 37
  • 1
    Have you had a look in the JavaScript profiler to see if this is even an issue? My guess: No. – tadman Nov 04 '14 at 17:32
  • No. This is as fast as it gets. – Aadit M Shah Nov 04 '14 at 17:32
  • [Here](http://stackoverflow.com/a/4298672/1169519) is a real debouncer. – Teemu Nov 04 '14 at 17:35
  • Maybe it's not realy heavy to processor but memory allocationg geting bigger even when event is fired only once... http://imgur.com/BdGwOQr (from this fiddle -> http://jsfiddle.net/hky0oekm/) – Bodzio Nov 04 '14 at 17:50

0 Answers0