Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

Wrap the request in setTimeout() and convert seconds to milliseconds: for example, a three-second delay is 3 * 1000. The timer postpones when the request starts; it does not pause or freeze the page. If the delay is meant to restart after each keystroke, clear the previous timer to debounce the request.

Delay a request with setTimeout()

setTimeout() schedules a function to run once after a delay expressed in milliseconds. Put the AJAX request inside that function so it does not start until the timer fires:

const delayMs = 3 * 1000;

const timerId = setTimeout(async () => {
  try {
    const response = await fetch('/api/items', { method: 'GET' });
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    const data = await response.json();
    render(data);
  } catch (error) {
    console.error(error);
  }
}, delayMs);

Replace 3 with the number of seconds you want to wait, and replace the URL and render() with your endpoint and page-update logic. The response.ok check matters because Fetch can fulfill its promise when a response arrives even if its HTTP status is an error such as 404.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The delay is a minimum target, not an exact wall-clock guarantee: a busy main thread, background-tab throttling, or nested-timer rules can make the callback run later. Negative delays behave like zero. MDN documents a maximum delay of 2,147,483,647 milliseconds (about 24.8 days); larger values can overflow. See MDN’s setTimeout() reference.

Cancel or restart a delay when the user acts again

If each new action should replace the pending request—for example, while someone types in a search box—clear the old timer before scheduling another. This pattern is called debouncing:

let timerId;

function searchLater(query) {
  clearTimeout(timerId);
  timerId = setTimeout(() => startSearch(query), 400);
}

Here the search starts only after the input has stayed unchanged for 400 milliseconds. clearTimeout() can stop a callback that has not started yet; it cannot stop a request after the callback has already sent it.

Abort a Fetch request that has already started

Use an AbortController when a newer search makes an in-flight request unnecessary. Abort the earlier controller before starting the replacement, pass its signal to Fetch, and ignore the expected AbortError:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
let controller;

async function startSearch(query) {
  controller?.abort();
  controller = new AbortController();

  try {
    const response = await fetch(
      `/api/search?q=${encodeURIComponent(query)}`,
      { signal: controller.signal }
    );
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    render(await response.json());
  } catch (error) {
    if (error.name !== 'AbortError') console.error(error);
  }
}

Assigning the controller’s signal makes the request cancelable; calling abort() rejects the Fetch promise with AbortError. This cancels the client-side request and response handling, but should not be treated as a guarantee that a server has undone work it already performed. See MDN’s Fetch API guidance.

Use jQuery or XMLHttpRequest

jQuery

To delay a jQuery AJAX request, put $.ajax() inside setTimeout(). Keep the returned jqXHR if you may need to abort it after it starts:

let timerId;
let jqXHR;

function loadLater() {
  clearTimeout(timerId);
  jqXHR?.abort();

  timerId = setTimeout(() => {
    jqXHR = $.ajax({ url: '/api/items', method: 'GET' });
  }, 3000);
}

jQuery’s timeout option is not a delay before sending: it limits how long the request may run, in milliseconds from the call to $.ajax(). jQuery also strongly discourages async: false, which can make the browser unresponsive. See the jQuery.ajax() documentation.

XMLHttpRequest

For direct XMLHttpRequest code, use setTimeout() around the code that opens and sends the request if you need a delayed start. Set xhr.timeout and handle ontimeout separately if you also need a limit on request duration. That timeout terminates an asynchronous request that exceeds the limit; it does not postpone the start. MDN describes Fetch as the more flexible and powerful replacement for XMLHttpRequest, while XMLHttpRequest remains a form of AJAX. See MDN’s XMLHttpRequest reference.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose the right timing pattern for repeated requests

Pattern When work starts Can cancel pending delay? Can stop an in-flight request? Main consideration
setTimeout() After the specified delay Yes, with clearTimeout() Not by itself; use the request API’s cancellation support Best for postponing one request.
Debounced setTimeout() After input or another trigger remains unchanged for the delay Yes; each trigger clears and replaces the timer Not by itself; abort separately if a request has started Prevents a burst of requests, but responses from earlier in-flight work still need handling.
setInterval() At recurring intervals Yes, with clearInterval() Not by itself Can start overlapping work when a request lasts longer than the interval.
Recursive setTimeout() After the previous work finishes, then after the chosen delay Yes, by clearing the next scheduled timeout Not by itself Useful for polling when request duration varies, because it avoids scheduling the next run over unfinished work.

For polling, schedule the next timeout only after the current request and its processing finish. MDN recommends recursive setTimeout() over setInterval() when work might take longer than the interval, since intervals can produce overlapping requests and out-of-order results. Even without overlap, separate requests can return in a different order than they were sent; abort obsolete requests or ensure only the latest result updates the page.

Delay and request timeout are different controls

A delayed start answers, “When should the browser send this request?” A request timeout answers, “How long should the browser wait for this request once it has started?” You can use both: schedule the request with setTimeout(), then configure the timeout on the request itself. Keep their millisecond values and purposes separate so a short request limit is not mistaken for a delay before sending.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.