microsoft/vscode-react-native
Publicmirrored from https://github.com/microsoft/vscode-react-nativeAvailable
src/common/executionsLimiter.ts
39lines · modeblame
7cc67271digeff10 years ago | 1 | // Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | // Licensed under the MIT license. See LICENSE file in the project root for details. | |
| 3 | | |
| 4 | /* This class can be used to limit how often can some code be executed e.g. Max once every 10 seconds */ | |
| 5 | export class ExecutionsLimiter { | |
34472878RedMickey5 years ago | 6 | private executionToLastTimestamp: { [id: string]: number } = {}; |
7cc67271digeff10 years ago | 7 | |
34472878RedMickey5 years ago | 8 | public execute(id: string, limitInSeconds: number, lambda: () => void): void { |
7cc67271digeff10 years ago | 9 | const now = new Date().getTime(); |
| 10 | | |
| 11 | const lastExecution = this.executionToLastTimestamp[id] || 0; | |
| 12 | if (now - lastExecution >= limitInSeconds * 1000) { | |
| 13 | this.executionToLastTimestamp[id] = now; | |
| 14 | lambda(); | |
| 15 | } | |
| 16 | } | |
| 17 | } | |
c2bf3c4fdigeff10 years ago | 18 | |
| 19 | export class ExecutionsFilterBeforeTimestamp { | |
| 20 | private static MILLISECONDS_IN_ONE_SECOND = 1000; | |
| 21 | | |
| 22 | private sinceWhenToStopFiltering: number; | |
| 23 | | |
| 24 | constructor(delayInSeconds: number) { | |
34472878RedMickey5 years ago | 25 | this.sinceWhenToStopFiltering = |
| 26 | this.now() + | |
| 27 | delayInSeconds * ExecutionsFilterBeforeTimestamp.MILLISECONDS_IN_ONE_SECOND; | |
c2bf3c4fdigeff10 years ago | 28 | } |
| 29 | | |
34472878RedMickey5 years ago | 30 | public execute(lambda: () => void): void { |
c2bf3c4fdigeff10 years ago | 31 | if (this.now() >= this.sinceWhenToStopFiltering) { |
| 32 | lambda(); | |
| 33 | } | |
| 34 | } | |
| 35 | | |
| 36 | private now(): number { | |
| 37 | return new Date().getTime(); | |
| 38 | } | |
| 39 | } |