Skip to content

Instantly share code, notes, and snippets.

Forked from PizzaBrandon/jquery.waituntilexists.js
Last active June 16, 2023 16:16
  • Star 10 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save md55/6565078 to your computer and use it in GitHub Desktop.
bugfix: if handler do waituntilexists() again with same selector then new IntervalId will replace old one in intervals array before removeListener() call. So new Interval will be cleared instead of old, and old Interval will never be cleared.
;(function ($, window) {
var intervals = {};
var removeListener = function(selector) {
if (intervals[selector]) {
intervals[selector] = null;
var found = 'waitUntilExists.found';
* @function
* @property {object} jQuery plugin which runs handler function once specified
* element is inserted into the DOM
* @param {function|string} handler
* A function to execute at the time when the element is inserted or
* string "remove" to remove the listener from the given selector
* @param {bool} shouldRunHandlerOnce
* Optional: if true, handler is unbound after its first invocation
* @example jQuery(selector).waitUntilExists(function);
$.fn.waitUntilExists = function(handler, shouldRunHandlerOnce, isChild) {
var selector = this.selector;
var $this = $(selector);
var $elements = $this.not(function() { return $(this).data(found); });
if (handler === 'remove') {
// Hijack and remove interval immediately if the code requests
else {
if (shouldRunHandlerOnce && $this.length) {
// Element was found, implying the handler already ran for all
// matched elements
// Run the handler on all found elements and mark as found
$elements.each(handler).data(found, true);
else if (!isChild) {
// Run the handler on all found elements and mark as found
$elements.each(handler).data(found, true);
// If this is a recurring search or if the target has not yet been
// found, create an interval to continue searching for the target
intervals[selector] = window.setInterval(function () {
$this.waitUntilExists(handler, shouldRunHandlerOnce, true);
}, 500);
return $this;
}(jQuery, window));
(function(e,f){var b={},g=function(a){b[a]&&(f.clearInterval(b[a]),b[a]=null)};e.fn.waitUntilExists=function(a,h,j){var c=this.selector,d=e(c),k=d.not(function(){return e(this).data("waitUntilExists.found")});"remove"===a?g(c):(k.each(a).data("waitUntilExists.found",!0),h&&d.length?g(c):j||(b[c]=f.setInterval(function(){d.waitUntilExists(a,h,!0)},500)));return d}})(jQuery,window);
Copy link

codedr1 commented Sep 16, 2014

Evgeniy: Could you please clarify what the license for this code is or whether it's in the public domain?

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