Javascript Delay

I have a handleScroll function that needs to be called when the scroll position of the window changes. Here is the code for this

 $(window).scroll(handleScroll); 

But the problem is that the above code ends up calling handleScroll too often. How to change the above code so that handleScroll is called only after the user has stopped scrolling for 200 milliseconds?

+4
source share
2 answers
 var timeoutHandle; $(window).scroll(function(e) { if (timeoutHandle) { clearTimeout(timeoutHandle); } timeoutHandle = setTimeout(function() { handleScroll(e); timeoutHandle = null; }, 200); }); 
+2
source

Using the underscorejs library, this can be easy as

 var debounceid = _.debounce(handleScroll, 200); $(window).resize(debounceid); 
0
source

All Articles