Web App Development

jQuery deferred objects and reporting progress

Previous posts on deferred objects: with $.ajax and your own components.

jQuery deferred objects allow you to report progress by calling the notify function. You can add a handler to promise objects with the progress function. (Promise objects are subsets of deferred objects that are returned to the observing code.)
function getExamplePromise() {
var def = $.Deferred();
var count = 0;
var interval = setInterval(function () {
count++;
def.notify(Math.round(count / 4 * 100) + "%")
if (count === 4) {
clearInterval(interval);
def.resolve();
}
}, 500);
return def.promise();
}

var promise = getExamplePromise();
promise.progress(function (progress) {
console.log("Progress report: " + progress);
});
promise.then(function () {
console.log("Done")
});
This will be printed in the console:
Progress report: 25%
Progress report: 50%
Progress report: 75%
Progress report: 100%
Done
You can use notifyWith if you want to set the execution context in the progress handler.

Comments


Follow me on Twitter
I'm building monitoring tool for site speed and Core Web Vitals.
➔ Start monitoring your website or run a free site speed test