jQuery Deferred notify Method Explained
Calling the .notify() method on a jQuery Deferred object
triggers any progress callbacks attached to that object, allowing you to
broadcast progress updates during an asynchronous operation before the
object is resolved or rejected. This overview covers the internal
mechanics of .notify(), when it executes, how it passes
data, and how it handles the Deferred object's lifecycle.
Execution of Progress Callbacks
When .notify() is invoked, jQuery executes all callbacks
previously registered using deferred.progress() or the
third argument of deferred.then(). The callbacks run in the
order they were added.
var deferred = $.Deferred();
deferred.progress(function(message) {
console.log("Progress: " + message);
});
deferred.notify("50% completed");
// Output: "Progress: 50% completed"Passing Arguments
Any arguments passed to .notify() are forwarded directly
to the progress handlers. You can pass single values, objects, or
multiple arguments to convey state, percentage completion, or status
messages:
deferred.notify(stepNumber, totalSteps, statusText);To set a custom execution context (this) for the
handlers, jQuery provides the companion method
deferred.notifyWith(context, [args]).
State Restrictions
The .notify() method is state-dependent:
- Pending State:
.notify()functions normally, immediately firing existing progress handlers and accepting new calls. - Resolved or Rejected State: Once a Deferred
transitions to either "resolved" (via
.resolve()) or "rejected" (via.reject()), any subsequent calls to.notify()are ignored. Progress callbacks will no longer execute.
Multiple Invocations
Unlike .resolve() and .reject(), which
permanently alter the Deferred's state and can only trigger completion
handlers once, .notify() can be called repeatedly as long
as the Deferred remains pending. This makes it ideal for streaming data,
measuring file upload/download progress, or notifying the UI of
multi-step task completion.