JSFiddle - React, Tailwind, and code Playground
by mission liao
HTML
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<p>
Write a JS module/object with a function that accepts 3 arguments: a CSS selector, a number n, and a callback.
</p>
<p>
The function will call the callback if any element matching the CSS selector already exists or exists within the next n seconds. The list of elements found will be passed in as the first argument to the callback. The callback should be called within 500ms of the element appearing on the page and should only be called once.
</p>
<p>
jQuery is available to use.
</p>
JavaScript
var interval = 400;
var Checker = (function() {
var timerHandlers = {};
var interval = 400;
var timer = function(sel, cb) {
var elms = document.querySelectorAll(sel);
var toClear = false;
if (elms.length > 0) {
cb(elms);
toClear = true;
} else {
this.timerHandlers[cb].remainMilli -= this.interval;
toClear = this.timerHandlers[cb].remainMilli <= 0;
}
if (toClear) {
var handler = this.timerHandlers[cb].handler;
clearInterval(handler);
delete this.timerHandlers[cb];
}
}
var check = function(sel, remain, cb) {
this.timerHandlers[cb] = {
remainMulli: remain * 1000,
handler: setInterval(timer.bind(null, sel, cb), interval),
}
};
return {
check: check,
};
})();
Checker.check("table", 5, function(elements) {
console.log("Table!");
console.dir(elements);
});