diff --git a/lib/services/hash.service.ts b/lib/services/hash.service.ts index 4cdb59641c..df38155986 100644 --- a/lib/services/hash.service.ts +++ b/lib/services/hash.service.ts @@ -1,15 +1,20 @@ 'use strict'; import { Injectable } from '@angular/core'; import { PlatformLocation } from '@angular/common'; - import { BehaviorSubject } from 'rxjs/BehaviorSubject'; +import { debounce } from '../utils/'; + @Injectable() export class Hash { public value = new BehaviorSubject(null); private noEmit:boolean = false; + private debouncedUpdate: (hash:string, rewrite: boolean) => void; + constructor(private location: PlatformLocation) { this.bind(); + + this.debouncedUpdate = debounce(this._update.bind(this), 100); } start() { @@ -28,6 +33,10 @@ export class Hash { } update(hash: string|null, rewriteHistory:boolean = false) { + this.debouncedUpdate(hash, rewriteHistory); + } + + private _update(hash: string|null, rewriteHistory:boolean = false) { if (hash == undefined) return; if (rewriteHistory) { window.history.replaceState(null, '', window.location.href.split('#')[0] + '#' + hash); @@ -39,4 +48,5 @@ export class Hash { this.noEmit = false; }); } + } diff --git a/lib/utils/helpers.ts b/lib/utils/helpers.ts index 1f7cc1b0bc..9ba5da9c7e 100644 --- a/lib/utils/helpers.ts +++ b/lib/utils/helpers.ts @@ -99,6 +99,21 @@ export function throttle(fn, threshhold, scope) { }; } +export function debounce(func, wait, immediate = false) { + var timeout; + return function() { + var context = this, args = arguments; + var later = function() { + timeout = null; + if (!immediate) func.apply(context, args); + }; + var callNow = immediate && !timeout; + clearTimeout(timeout); + timeout = setTimeout(later, wait); + if (callNow) func.apply(context, args); + }; +} + export const isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0 || (function (p) { return p.toString() === '[object SafariRemoteNotification]'; })(!window['safari'] || safari.pushNotification);