import { Debug } from "../utils" ; import Deque = require ( "denque" ) ; const debug = Debug ( "delayqueue" ) ; export interface export interface IDelayQueueOptions { callback ? : Function ; timeout : number ; } export class export default class DelayQueue { private queues : { [ key ] : any | null ; } = { } ; private timeouts : { [ key ] : NodeJS . Timer ; } = { } ; param { string } bucket param { Function } item param { IDelayQueueOptions } options memberof public push ( bucket , item , options ) { const callback = options . callback || process . nextTick ; if ( ! this . queues [ bucket ] ) { this . queues [ bucket ] = new Deque ( ) ; } const queue = this . queues [ bucket ] ; queue . push ( item ) ; if ( ! this . timeouts [ bucket ] ) { this . timeouts [ bucket ] = setTimeout ( ( ) => { callback ( ( ) => { this . timeouts [ bucket ] = null ; this . execute ( bucket ) ; } ) ; } , options . timeout ) ; } } private execute ( bucket ) { const queue = this . queues [ bucket ] ; if ( ! queue ) { return ; } const { length } = queue ; if ( ! length ) { return ; } debug ( "send %d commands in %s queue" , length , bucket ) ; this . queues [ bucket ] = null ; while ( queue . length > 0 ) { queue . shift ( ) ( ) ; } } }