/**
 * Allows one to perform an action in a chaotic (in regard to time) system.
 */
class Ifterval {
    
    condition   = null;
    action      = null;
    interval    = 100;
    attempts    = 0;
    maxAttempts = 2;
    
    timerHandle = null;
    
    constructor(
        conditionCallback,
        actionCallback,
        maxAttempts = 2,
        interval = 100,
    ) {
        this.condition   = conditionCallback;
        this.action      = actionCallback;
        this.interval    = interval;
        this.maxAttempts = maxAttempts;
        
        var self = this;
        
        this.timerHandle = setInterval(function () {
            
            self.attempts++;
            
            if (self.attempts >= self.maxAttempts) {
                clearInterval(self.timerHandle);
                self.timerHandle = null;
            }
            
            if (self.condition()) {
                try {
                    self.action.call(this);
                } catch (e) {
                    console.error(e);
                }
                clearInterval(self.timerHandle);
                self.timerHandle = null;
            }
            
        }, this.interval);
    }
    
}