Throttle scroll event

This commit is contained in:
Roman Hotsiy 2016-08-22 12:18:56 +03:00
parent 379870a1b3
commit 5efbd97f3e
No known key found for this signature in database
GPG Key ID: 5CB7B3ACABA57CB0
2 changed files with 27 additions and 1 deletions

View File

@ -2,6 +2,7 @@
import { Injectable, EventEmitter, Output } from '@angular/core';
import { BrowserDomAdapter } from '@angular/platform-browser/src/browser/browser_adapter';
import { OptionsService } from './options.service';
import { throttle } from '../utils/helpers';
export const INVIEW_POSITION = {
ABOVE : 1,
@ -60,7 +61,8 @@ export class ScrollService {
bind() {
this.prevOffsetY = this.scrollY();
this._cancel = this.dom.onAndCancel(this.$scrollParent, 'scroll', (evt) => { this.scrollHandler(evt); });
this._cancel = this.dom.onAndCancel(this.$scrollParent, 'scroll',
throttle((evt) => { this.scrollHandler(evt); }, 100, this));
}
unbind() {

View File

@ -89,3 +89,27 @@ export function safePush(obj, prop, val) {
if (!obj[prop]) obj[prop] = [];
obj[prop].push(val);
}
// credits https://remysharp.com/2010/07/21/throttling-function-calls
export function throttle(fn, threshhold, scope) {
threshhold = threshhold || 250;
var last,
deferTimer;
return function () {
var context = scope || this;
var now = +new Date,
args = arguments;
if (last && now < last + threshhold) {
// hold on to it
clearTimeout(deferTimer);
deferTimer = setTimeout(function () {
last = now;
fn.apply(context, args);
}, threshhold);
} else {
last = now;
fn.apply(context, args);
}
};
}