Asynchronous messaging

JavaScript runs in a single thread inside browsers. When the thread is busy, asynchronous events like user actions or XHR responses get queued up and only get processed when the currently running JavaScript execution thread becomes idle.

Suppose you want to fire off an event but don’t want the code for handling that event to be run immediately:

if (!this.fmt.test(this.value)) {
    this.fireEvent("invalid"); // Synchronous processing!
    this.markInvalid(true);
}

You can use window.setTimeout to bring asynchronousity to the firing and processing of the event:

if (!this.fmt.test(this.value)) {
    var that = this;
    setTimeout(function () {
        that.fireEvent("invalid");
    }, 1);
    this.markInvalid(true);
}

If you use a 0 millisecond timeout, some JavaScript engines may short-circuit it to an immediate functional call, beating the purpose of using setTimeout. 1 millisecond allows a short-circuit-free minimum delay. Note that some engines may have a minimum timer resolution of 10 milliseconds or so.