Real $.wait() for jquery
It somewhat follows the jQuery.animate() syntax - allows to be chained with other fx functions, supports 'slow' and other jQuery.fx.speeds as well as being fully jQuery. And will be handled the same way as animations, if you stop those. Note: since wait adds to the animation stack, $.css() is executed immediately - as it is supposed: expected jQuery behaviour.
by BananaAcid
HTML
<ol id="result"></ol>
<!--
The core of the sulution is: as ES6
$('<queue/>')
.delay(100)
.queue( (next) => { $('#result').text('done.'); next(); } );
explaination:
1. pseudo element, being able to hold a jQuery animation queue
2. adding a delay into the fx queue
3. adding a callback to the fx queue to executed
3.1. calling the passed in next(), to signal the end of the async callback, and to continue in the fx queue
that least to the following possible usage:
$('#div1')
.fadeIn(200)
.delay(100).queue( (next) => { $('#div1').text('done.'); next(); } )
.fadeOut(100);
-->
JavaScript
/**
* Real Wait for jQuery
*
* @autor Nabil Redmann <repo+jsfiddle@BananaAcid.de>
**/
// add wait as $.wait() standalone and $(elem).wait() for animation chaining, all jquery animation functions apply (as well as .stop())
(function($) {
$.wait = function(duration, completeCallback, target) {
$target = $(target || '<queue />');
return $target.delay(duration).queue(function(next){completeCallback && completeCallback.call($target); next();});
};
$.fn.wait = function(duration, completeCallback) {
return $.wait.call(this, duration, completeCallback, this);
};
})(jQuery);
//TEST and usage
$(function() {
// stand alone
$.wait(1000, function() {
$('#result')
.append('<li>standalone @ 1000ms');
});
// keep a reference to the fx queue (which NOT referencing a visible DOM element)
var $timeout = $.wait(1000, function() {
$('#result').append('<li>$timeout @ 1000ms');
});
// we append a second timeout to $timeout
$timeout.wait(2000, function() {
$('#result').append('<li>$timeout @ 2000ms');
});
// chained
$('#result')
.append('<li>chained (1) @ 0ms')
.wait('slow', function() {
$(this).append('<li>chained (2) + ' + jQuery.fx.speeds.slow);
// ! all jquery FX Queue functions apply !
// we cancel the wait and dismiss(true) the rendering
$timeout.stop(true);
})
.wait('slow', function() {
$(this).append(
'<li>chained (3) + '
+ jQuery.fx.speeds.slow + 'ms'
+ ' -> @ ' + (2 * jQuery.fx.speeds.slow) + 'ms'
);
})
.css({color: 'green'});
});