aboutsummaryrefslogblamecommitdiffstats
path: root/packages/utils/src/interval_utils.ts
blob: 6784d5b35743bb2f643fe9be5aa339a769720ff8 (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 isLocked = false;
        const intervalId = setInterval(async () => {
            if (isLocked) {
                return;
            } else {
                isLocked = true;
                try {
                    await fn();
                } catch (err) {
                    onError(err);
                }
                isLocked = 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);
    },
};