Understanding the jQuery $.now() Function

This article provides an overview of the jQuery $.now() function, explaining what it does, how it is implemented under the hood, and how it compares to native JavaScript. You will learn the syntax, return value, practical use cases such as cache-busting and timing measurements, and why modern web development often uses native alternatives instead.

What is jQuery $.now()?

The $.now() function is a core utility method in the jQuery library that returns the current time in milliseconds. Specifically, it outputs an integer representing the number of milliseconds that have elapsed since the Unix Epoch (January 1, 1970, 00:00:00 UTC).

Syntax and Basic Usage

The function takes no parameters and is called directly on the jQuery object:

let timestamp = $.now();
console.log(timestamp); // Example output: 1716301234567

How It Works Internally

Under the hood, $.now() acts as a shorthand alias for native JavaScript date handling. In modern versions of jQuery, the implementation is straightforward:

jQuery.now = function() {
    return Date.now();
};

In older versions of jQuery (prior to broad browser support for ECMAScript 5), $.now() included a fallback to ensure cross-browser compatibility:

jQuery.now = function() {
    return (new Date()).getTime();
};

Regardless of the jQuery version, the function avoids the manual creation of a new Date() object in your own application code, returning the numerical timestamp directly.

Common Use Cases

  1. Cache Busting in AJAX Requests
    Browsers often aggressively cache HTTP GET requests. Appending a unique timestamp generated by $.now() to the URL query string forces the browser to fetch a fresh version of the resource from the server:

    $.ajax({
        url: "/api/data?_=" + $.now(),
        method: "GET",
        success: function(response) {
            console.log(response);
        }
    });
  2. Measuring Execution Time
    You can calculate how long an operation takes to execute by recording the timestamp before and after the operation:

    let start = $.now();
    
    // Perform an intensive task
    for (let i = 0; i < 1000000; i++) {}
    
    let duration = $.now() - start;
    console.log("Elapsed time: " + duration + " ms");
  3. Generating Pseudo-Unique Identifiers
    Because time constantly moves forward, $.now() is frequently used to create temporary, semi-unique identifiers for dynamically created DOM elements or transient state keys.

Modern Alternative

Because modern browsers fully support standard ECMAScript 5 features, native Date.now() is identical in performance, functionality, and return value to $.now(). If you are not already using jQuery in your project, native JavaScript should be preferred:

const timestamp = Date.now();