Last active
January 3, 2016 14:18
-
-
Save tytskyi/8474947 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: