aboutsummaryrefslogblamecommitdiffstats
path: root/packages/utils/src/interval_utils.ts
blob: 6984bf42d48c5ec8ec7636a2e12e611958c2dfdd (plain) (tree)
1
2
3
4
5
6
7
8
9
                            
 
                              




                                      
                           
                                                    
                         

                       
                              




                                 
                               
             
                       
                          
      
                                                                 
                                  
      
                                                                                                  











                                                   
  
import * as _ from 'lodash';

export const intervalUtils = {
    setAsyncExcludingInterval(
        fn: () => Promise<void>,
        intervalMs: number,
        onError: (err: Error) => void,
    ): NodeJS.Timer {
        let locked = false;
        const intervalId = setInterval(async () => {
            if (locked) {
                return;
            } else {
                locked = true;
                try {
                    await fn();
                } catch (err) {
                    onError(err);
                }
                locked = false;
            }
        }, intervalMs);
        return intervalId;
    },
    clearAsyncExcludingInterval(intervalId: NodeJS.Timer): void {
        clearInterval(intervalId);
    },
    setInterval(fn: () => void, intervalMs: number, onError: (err: Error) => void): NodeJS.Timer {
        const intervalId = setInterval(() => {
            try {
                fn();
            } catch (err) {
                onError(err);
            }
        }, intervalMs);
        return intervalId;
    },
    clearInterval(intervalId: NodeJS.Timer): void {
        clearInterval(intervalId);
    },
};