import * as Debug from 'debug' ; const debug = Debug ( 'musicbrainz-api:rate-limiter' ) ; export class RateLimiter { public static sleep ( ms ) { return new Promise ( resolve => setTimeout ( resolve , ms ) ) ; } public queue : number [ ] = [ ] ; private readonly period : number ; public constructor ( period , private maxCalls ) { this . period = 1000 * period ; } public async limit ( ) { let now = new Date ( ) . getTime ( ) ; const t0 = now - ( this . period ) ; while ( this . queue . length > 0 && this . queue [ 0 ] < t0 ) { this . queue . shift ( ) ; } if ( this . queue . length >= this . maxCalls ) { const delay = this . queue [ 0 ] + this . period - now ; debug ( `Client side rate limiter activated: cool down for ${ delay / 1000 } s...` ) ; return RateLimiter . sleep ( delay ) ; } now = new Date ( ) . getTime ( ) ; this . queue . push ( now ) ; } }