Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throttling with Lodash doesn't work

I want to use Lodash's throttle to have fewer function invokes on scroll. My code is as follows:

window.addEventListener('scroll', _.throttle(() => { console.log('bam'); }), 1000);

Unfortunately, this doesn't work - I am getting bam-ed all the time, and not every one secound.

What can I do?

CodePen: http://codepen.io/tomekbuszewski/pen/oxeOXy?editors=1111

like image 229
Tomek Buszewski Avatar asked Mar 31 '16 08:03

Tomek Buszewski


Video Answer


1 Answers

The _.throttle function should only be generated once and not every time the event fires

 var callback = _.throttle(() => { console.log('bam')}, 10000);
    window.addEventListener('scroll', callback);
div {
 height : 100px
}
div > div {
 height : 1000px
}
<script src="https://cdn.jsdelivr.net/lodash/4.6.1/lodash.min.js"></script>
<div>
  <div></div>
</div>

the console.log("bam") called once every 10 sec

like image 91
Zamboney Avatar answered Oct 11 '22 23:10

Zamboney