From: Chocobozzz Date: Mon, 18 Jun 2018 08:04:08 +0000 (+0200) Subject: Improve screen cache service X-Git-Tag: v1.0.0-beta.9~29 X-Git-Url: https://git.librecmc.org/?a=commitdiff_plain;h=fc11a44ec9d12af915ac72d8106cb934cfcdcbcd;p=oweals%2Fpeertube.git Improve screen cache service --- diff --git a/client/src/app/shared/misc/screen.service.ts b/client/src/app/shared/misc/screen.service.ts index 5b17a914a..2e01839b2 100644 --- a/client/src/app/shared/misc/screen.service.ts +++ b/client/src/app/shared/misc/screen.service.ts @@ -1,23 +1,37 @@ -import { Injectable, NgZone } from '@angular/core' +import { Injectable } from '@angular/core' @Injectable() export class ScreenService { private windowInnerWidth: number + private lastFunctionCallTime: number + private cacheForMs = 500 - constructor (private zone: NgZone) { - this.windowInnerWidth = window.innerWidth - - // Try to cache a little bit window.innerWidth - this.zone.runOutsideAngular(() => { - setInterval(() => this.windowInnerWidth = window.innerWidth, 500) - }) + constructor () { + this.refreshWindowInnerWidth() } isInSmallView () { - return this.windowInnerWidth < 600 + return this.getWindowInnerWidth() < 600 } isInMobileView () { - return this.windowInnerWidth < 500 + return this.getWindowInnerWidth() < 500 + } + + // Cache window inner width, because it's an expensive call + private getWindowInnerWidth () { + if (this.cacheWindowInnerWidthExpired()) this.refreshWindowInnerWidth() + + return this.windowInnerWidth + } + + private refreshWindowInnerWidth () { + this.lastFunctionCallTime = new Date().getTime() + + this.windowInnerWidth = window.innerWidth + } + + private cacheWindowInnerWidthExpired () { + return new Date().getTime() > (this.lastFunctionCallTime + this.cacheForMs) } }