Skip to content

Instantly share code, notes, and snippets.

@tytskyi
Last active January 3, 2016 14:18
Show Gist options
  • Save tytskyi/8474947 to your computer and use it in GitHub Desktop.
Save tytskyi/8474947 to your computer and use it in GitHub Desktop.
wait = function (data) {
var check, context, fail, freq, isResetFunction, reset, resetAllTimers, success, timers, waitInner;
timers = {};
resetAllTimers = function () {
clearTimeout(timers.timer);
return clearTimeout(timers.resetTimer);
};
check = data.check || null;
freq = data.frequency || data.freq || 0;
reset = data.reset || null;
context = data.context || global || window.top;
if (typeof data.success === 'function') {
success = function () {
resetAllTimers();
data.success();
return typeof data.always === "function" ? data.always() : void 0;
};
} else {
success = function () {
resetAllTimers();
return typeof data.always === "function" ? data.always() : void 0;
};
}
if (typeof data.fail === 'function') {
fail = function () {
resetAllTimers();
data.fail();
return typeof data.always === "function" ? data.always() : void 0;
};
} else {
fail = function () {
resetAllTimers();
return typeof data.always === "function" ? data.always() : void 0;
};
}
isResetFunction = typeof reset === 'function' ? true : false;
if (!isResetFunction) {
reset = parseInt(reset, 10);
reset = reset > -1 ? reset : null;
}
if (!check) {
if (data.id) {
check = function () {
return context.document.getElementById(data.id);
};
} else if (data.selector) {
check = function () {
return context.document.querySelector(data.selector);
};
} else {
throw new Error("wait: no condition specified");
}
}
if (check()) {
success();
} else if (isResetFunction && reset()) {
fail();
} else {
waitInner = function (data) {
timers.timer = setTimeout(function() {
if (check()) {
success();
} else {
if (isResetFunction && reset()) {
fail();
} else {
waitInner(data);
}
}
}, freq);
};
if (reset && !isResetFunction) {
timers.resetTimer = setTimeout(function() {
return fail();
}, reset);
}
waitInner(data);
}
};
@tytskyi
Copy link
Author

tytskyi commented Apr 24, 2014

Usage:

// with reset timer
wait({
    freq: 100,
    reset: 3000,
    check: function () {
        return window.jQuery;
    },
    success: function () {
        console.log('jQuery was found')
    },
    fail: function () {
        console.log('jQuery wasn\'t found during 3 seconds')
    },
    always: function () {
        console.log('Anyway print something')
    }
});

// with reset function
wait({
    freq: 100,
    reset: function () {
        return 2 + 2 > -1;
    },
    check: function () {
        return window.Zepto;
    },
    success: function () {
        console.log('Zepto was found')
    },
    fail: function () {
        console.log('Zepto wasn\'t found')
    },
    always: function () {
        console.log('Anyway print something')
    }
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment