开发者

How to condense/collate multiple jQuery events into one event on a time delay?

I want to condense multiple events into a single event on a time delay. I don't need my bound function to be called repeatedly for really common things like mouse movement and page scrolling. At most, once every half second would be plenty if there is a queued event to fire.

For the sake of a more concrete example:

Let's say I bind to jQuery(...).scroll() with a somewhat expensive function. As the user scrolls the page, this will get called hundreds, possibly thousands of times. I want to condense all those events into one event call per .5 seconds, sending the most recent event to the handler after .5 seconds has passed and IGNORING previous events that would have fired.

Visually:

  • 15:20:35.000 - User scroll event. Timer starts. New event stored.
  • 15:20:35.020 - User scroll event. Replace stored event.
  • 15:20:35.100 - User scroll event. Replace stored event.
  • 15:20:35.371 - User scroll event. Replace stored event.
  • 15:20:35.500 - Timer expires. Event开发者_C百科 from 15:20:35.371 is sent to the registered handler/callback. None of the earlier events get sent.

BTW, a couple months ago I found a jQuery plugin somewhere that specifically did exactly this and had some nice features too but now I can't find it again or any similar plugin. I would much rather find a working plugin than reinvent the wheel and hack together a solution (but I'll take the hack).


Here is a jQuery plugin (not by me) that introduces the scrollstart and scrollend events. You can change the time delay inside the function by modifying the latency parameter. I am using this in a current project, and it works great.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜