JavaScript Callbacks and Timers: setTimeout, setInterval and Polling

Before promises existed, all asynchronous JavaScript was written with callbacks: “do this, and call me back when you are done”. You still meet callbacks everywhere, in timers, event listeners, Node.js core APIs and older libraries, and timers are the building blocks of retries, polling and timeouts in test helpers. In this lesson you will learn to schedule and cancel work with setTimeout and setInterval, understand Node.js error-first callbacks, see why deeply nested callbacks became a problem, and build a reliable polling helper.

Advertisement

📖 What You’ll Learn: asynchronous callbacks, setTimeout and passing arguments, clearTimeout, setInterval and clearInterval, why setInterval can drift and the recursive setTimeout pattern, error-first callbacks in Node.js, callback hell and how to flatten it, timers that return promises (node:timers/promises), cancelling with AbortController, and a waitFor polling helper with a timeout.


📞 Asynchronous Callbacks

Definition: an asynchronous callback is a function you pass to an API that will call it later, when something has happened: a timer has expired, a file has been read, a button has been clicked. The code after the call keeps running in the meantime.

📄 async-callback.js

function fetchUser(id, onDone) {
  console.log(`requesting user ${id}...`);
  setTimeout(() => {
    onDone({ id, name: "Asha" });     // call back later with the result
  }, 20);
}

fetchUser(7, (user) => console.log("got user:", user.name));
console.log("request sent, doing other work");

⌨️ Terminal

node async-callback.js

🖥️ Output

requesting user 7...
request sent, doing other work
got user: Asha

The result is only available inside the callback. Code written after fetchUser(...) runs before the user arrives, a constant source of beginner bugs:

📄 too-early.js

let user;
setTimeout(() => { user = { name: "Asha" }; }, 10);
console.log("user right after scheduling:", user);   // not set yet

⌨️ Terminal

node too-early.js

🖥️ Output

user right after scheduling: undefined

⏲️ setTimeout and clearTimeout

setTimeout(callback, delayMs, ...args) runs the callback once, after at least delayMs milliseconds. Extra arguments are passed to the callback. It returns a timer ID (an object in Node.js, a number in browsers) that you can pass to clearTimeout to cancel it.

📄 set-timeout.js

const greet = (name, role) => console.log(`Hello ${name}, ${role}`);

setTimeout(greet, 20, "Asha", "tester");      // arguments after the delay

const reminder = setTimeout(() => console.log("this never prints"), 50);
clearTimeout(reminder);                        // cancelled before it ran

setTimeout(() => console.log("done after 30 ms"), 30);
console.log("timers scheduled");

⌨️ Terminal

node set-timeout.js

🖥️ Output

timers scheduled
Hello Asha, tester
done after 30 ms

⚠️ Watch out: Pass the function, do not call it: setTimeout(greet("Asha"), 1000) runs greet immediately and passes its return value (undefined) to setTimeout.


🔁 setInterval and clearInterval

setInterval(callback, intervalMs) runs the callback repeatedly, every intervalMs milliseconds, until you stop it with clearInterval. Always keep the ID and always stop the interval, or it runs forever and keeps a Node.js process alive.

📄 set-interval.js

let count = 0;
const id = setInterval(() => {
  count++;
  console.log(`heartbeat ${count}`);
  if (count === 3) {
    clearInterval(id);
    console.log("stopped");
  }
}, 20);

⌨️ Terminal

node set-interval.js

🖥️ Output

heartbeat 1
heartbeat 2
heartbeat 3
stopped
Advertisement

Recursive setTimeout instead of setInterval

setInterval schedules the next run on a fixed clock, even if the previous run (for example a slow network call) has not finished. A recursive setTimeout schedules the next run only after the current one completes, so runs never overlap and the gap can change dynamically:

📄 recursive-timeout.js

let attempt = 0;

function poll() {
  attempt++;
  const delay = 10 * 2 ** attempt;     // back off: 20, 40, 80 ms
  console.log(`attempt ${attempt}, next check in ${delay} ms`);
  if (attempt < 3) setTimeout(poll, delay);
  else console.log("finished polling");
}

poll();

⌨️ Terminal

node recursive-timeout.js

🖥️ Output

attempt 1, next check in 20 ms
attempt 2, next check in 40 ms
attempt 3, next check in 80 ms
finished polling

⚠️ Error-First Callbacks in Node.js

Definition: Node.js core callback APIs follow the error-first convention: the callback’s first argument is an error (or null when everything went well), and the result comes after it. Always check the error before using the result.

📄 error-first.js

const fs = require("node:fs");

fs.writeFileSync("users.json", JSON.stringify([{ name: "Asha" }]));

fs.readFile("users.json", "utf8", (err, text) => {
  if (err) {
    console.log("could not read:", err.code);
    return;                           // stop here on error
  }
  console.log("users:", JSON.parse(text).length);
});

fs.readFile("missing.json", "utf8", (err, text) => {
  if (err) {
    console.log("could not read:", err.code);
    return;
  }
  console.log(text);
});

⌨️ Terminal

node error-first.js

🖥️ Output

could not read: ENOENT
users: 1

⚠️ Watch out: A try...catch around fs.readFile(...) does not catch errors from the callback: the callback runs later, after the try block has finished. That is why the error is passed in as an argument instead.

Writing your own function in this style:

📄 own-error-first.js

function divideLater(a, b, callback) {
  setTimeout(() => {
    if (b === 0) return callback(new Error("Division by zero"));
    callback(null, a / b);
  }, 5);
}

divideLater(10, 2, (err, result) => console.log(err ? err.message : `result ${result}`));
divideLater(10, 0, (err, result) => console.log(err ? err.message : `result ${result}`));

⌨️ Terminal

node own-error-first.js

🖥️ Output

result 5
Division by zero

🌀 Callback Hell

When each step depends on the previous one, callbacks nest inside callbacks. The code drifts to the right, error handling is repeated at every level, and the flow is hard to follow. This shape is called callback hell or the “pyramid of doom”:

📄 callback-hell.js

const api = {
  login: (user, cb) => setTimeout(() => cb(null, { token: "t-123" }), 5),
  getCart: (token, cb) => setTimeout(() => cb(null, { items: 2 }), 5),
  checkout: (cart, cb) => setTimeout(() => cb(cart.items ? null : new Error("empty cart"), { orderId: 451 }), 5),
};

api.login("asha", (err, session) => {
  if (err) return console.log("login failed", err);
  api.getCart(session.token, (err, cart) => {
    if (err) return console.log("cart failed", err);
    api.checkout(cart, (err, order) => {
      if (err) return console.log("checkout failed", err);
      console.log("order placed:", order.orderId);
    });
  });
});

⌨️ Terminal

node callback-hell.js

🖥️ Output

order placed: 451

Three steps already need three nesting levels and three error checks. Promises and async/await (the next lessons) were created to solve exactly this. The same flow with await becomes four flat lines inside one try...catch.

💡 Tip: If you must work with callbacks, flatten them with small named functions instead of anonymous nested ones, or convert the API to promises with util.promisify (shown in the Promises lesson).


Advertisement

⏳ Promise-Based Timers in Node.js

Node.js provides promise versions of the timers in node:timers/promises. They work with await, which reads much more naturally than callbacks:

📄 timers-promises.js

const { setTimeout: sleep, setInterval: every } = require("node:timers/promises");

async function main() {
  console.log("waiting 20 ms...");
  const value = await sleep(20, "timer value");
  console.log("woke up with:", value);

  let n = 0;
  for await (const _ of every(10)) {       // async iteration over an interval
    console.log("tick", ++n);
    if (n === 3) break;                     // break also stops the interval
  }
}
main();

⌨️ Terminal

node timers-promises.js

🖥️ Output

waiting 20 ms...
woke up with: timer value
tick 1
tick 2
tick 3

In browsers (and in Node.js too), the common one-line helper is const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));.


🛑 Cancelling with AbortController

Definition: an AbortController creates a signal that can be passed to cancellable APIs (promise timers, fetch, event listeners). Calling controller.abort() cancels them all. AbortSignal.timeout(ms) creates a signal that aborts by itself after a delay.

📄 abort.js

const { setTimeout: sleep } = require("node:timers/promises");

async function main() {
  const controller = new AbortController();
  setTimeout(() => controller.abort(), 20);          // cancel after 20 ms

  try {
    await sleep(1000, null, { signal: controller.signal });
    console.log("finished waiting");
  } catch (e) {
    console.log(`${e.name}: wait was cancelled`);
  }

  try {
    await sleep(1000, null, { signal: AbortSignal.timeout(15) });
  } catch (e) {
    console.log(`${e.name}: gave up after the timeout`);
  }
}
main();

⌨️ Terminal

node abort.js

🖥️ Output

AbortError: wait was cancelled
AbortError: gave up after the timeout

You will use the same signal option with fetch in the Fetch API lesson to stop requests that take too long.


🧪 Tester Scenario: A waitFor Polling Helper

Many test situations need “check this repeatedly until it is true, but give up after a timeout”: an email arriving in a test inbox, a background job finishing, an order status changing. This helper does it with a recursive setTimeout and reports a clear error when the timeout is reached:

📄 wait-for.js

function waitFor(check, { timeout = 1000, interval = 50, message = "condition" } = {}) {
  const start = Date.now();
  return new Promise((resolve, reject) => {
    let attempts = 0;
    function tick() {
      attempts++;
      const value = check();
      if (value) return resolve({ value, attempts });
      if (Date.now() - start >= timeout) {
        return reject(new Error(`Timed out after ${timeout} ms waiting for ${message} (${attempts} attempts)`));
      }
      setTimeout(tick, interval);
    }
    tick();
  });
}

// Simulated backend: the order becomes "shipped" after ~120 ms
const order = { status: "processing" };
setTimeout(() => { order.status = "shipped"; }, 120);

waitFor(() => order.status === "shipped" && order.status, { timeout: 500, interval: 50, message: "order to ship" })
  .then(({ value, attempts }) => console.log(`status: ${value} (checked ${attempts >= 3 ? "3 or more" : attempts} times)`))
  .then(() => waitFor(() => order.status === "delivered", { timeout: 150, interval: 50, message: "order delivery" }))
  .catch((e) => console.log(e.message.replace(/\(\d+ attempts\)/, "(several attempts)")));

⌨️ Terminal

node wait-for.js

🖥️ Output

status: shipped (checked 3 or more times)
Timed out after 150 ms waiting for order delivery (several attempts)
  • The check runs immediately, then every interval ms, and never overlaps itself.
  • The error message names what was being waited for, so a failing test explains itself.
  • Playwright has this built in: await expect.poll(() => getStatus()).toBe("shipped") and await expect(async () => {...}).toPass(). Use those inside Playwright tests.

Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Print "3", "2", "1", "Go!" with 10 ms between each using setTimeout (not setInterval).

Show answer

📄 practice1.js

function countdown(n) {
  if (n === 0) return console.log("Go!");
  console.log(String(n));
  setTimeout(() => countdown(n - 1), 10);
}
countdown(3);

🖥️ Output

3
2
1
Go!

Q2. Use setInterval to print the numbers 1 to 5, then stop the interval.

Show answer

📄 practice2.js

let n = 0;
const id = setInterval(() => {
  console.log(++n);
  if (n === 5) clearInterval(id);
}, 10);

🖥️ Output

1
2
3
4
5

Q3. Schedule a “session expired” message for 100 ms, but cancel it because the user “clicked” after 20 ms. Print what happened.

Show answer

📄 practice3.js

const expiry = setTimeout(() => console.log("session expired"), 100);
setTimeout(() => {
  clearTimeout(expiry);
  console.log("user active: expiry cancelled");
}, 20);

🖥️ Output

user active: expiry cancelled

Q4. Write an error-first function parseJsonLater(text, cb) that calls back with an error for invalid JSON and with the parsed value otherwise. Test it with valid and invalid input.

Show answer

📄 practice4.js

function parseJsonLater(text, cb) {
  setTimeout(() => {
    try {
      cb(null, JSON.parse(text));
    } catch (e) {
      cb(e);
    }
  }, 0);
}
parseJsonLater('{"a":1}', (err, data) => console.log(err ? "error" : data));
parseJsonLater("{a:1}", (err, data) => console.log(err ? `error: ${err.name}` : data));

🖥️ Output

{ a: 1 }
error: SyntaxError

Q5. Use sleep from node:timers/promises with await to print "step 1", wait 20 ms, then print "step 2".

Show answer

📄 practice5.js

const { setTimeout: sleep } = require("node:timers/promises");
(async () => {
  console.log("step 1");
  await sleep(20);
  console.log("step 2");
})();

🖥️ Output

step 1
step 2

Q6. Explain why this prints undefined and fix it so the total is printed.

let total;
setTimeout(() => { total = 42; }, 10);
console.log(total);
Show answer

The callback runs after 10 ms, but console.log runs immediately, before total is set. Use the value inside the callback (or await a promise):

📄 practice6.js

setTimeout(() => {
  const total = 42;
  console.log(total);
}, 10);

🖥️ Output

42

🧠 MCQ Quiz: Callbacks and Timers

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What does setTimeout return?
  2. How do you pass arguments to a setTimeout callback?
  3. How do you stop a setInterval?
  4. What is the first argument of a Node.js error-first callback?
  5. Why can’t try/catch around fs.readFile catch its errors?
  6. What is callback hell?
  7. What is an advantage of recursive setTimeout over setInterval?
  8. What does AbortSignal.timeout(500) create?
  9. What is wrong with setTimeout(save(), 1000)?
  10. Which Playwright API replaces a hand-written polling helper?

💼 Interview Questions and Answers

Q1. What is the difference between setTimeout and setInterval?

setTimeout runs a callback once after a minimum delay; setInterval runs it repeatedly at a fixed interval until clearInterval. Intervals do not wait for the previous run to finish, so slow callbacks can overlap or pile up; a recursive setTimeout avoids that and allows back-off. Both delays are minimums.

Q2. What are error-first callbacks?

A Node.js convention where the callback signature is (err, result): err is null on success or an Error on failure. The caller checks err first and returns early on failure. It exists because exceptions thrown in a later callback cannot be caught by the original caller’s try...catch.

Q3. How would you convert a callback-based function to a promise?

📄 promisify.js

const util = require("node:util");

function legacyAdd(a, b, cb) {
  setTimeout(() => cb(null, a + b), 5);
}

const addAsync = util.promisify(legacyAdd);
addAsync(2, 3).then((sum) => console.log("promisified:", sum));

const manual = (a, b) => new Promise((resolve, reject) =>
  legacyAdd(a, b, (err, result) => (err ? reject(err) : resolve(result))));
manual(4, 5).then((sum) => console.log("manual:", sum));

⌨️ Terminal

node promisify.js

🖥️ Output

promisified: 5
manual: 9

util.promisify works for any error-first callback API; the manual version shows what it does.

Q4. How do you implement waiting for a condition with a timeout?

Check the condition immediately; if it is not met and the timeout has not elapsed, schedule another check with setTimeout after an interval; resolve when it is met and reject with a descriptive error when time runs out. Use a recursive timeout (not an interval) so checks never overlap, and support cancellation with an AbortSignal. In Playwright tests, prefer expect.poll or toPass.


Advertisement

❓ Frequently Asked Questions

🤔 Is setTimeout precise?

No. The delay is a minimum: the callback runs when the time has passed and the call stack is free. Browsers also slow down timers in background tabs.

🤔 What is the maximum delay for setTimeout?

About 24.8 days (231 − 1 ms). Larger values overflow and the callback runs almost immediately, with a warning in Node.js.

🤔 Why does my Node.js script not exit?

An active interval, timer, server or open handle keeps the process alive. Clear intervals and close servers, or call timer.unref() for timers that should not keep the process running.

🤔 Should I still write callback-based code?

For new asynchronous code, use promises and async/await. Callbacks remain normal for events, array methods and timers.


🏁 Summary

  • Asynchronous callbacks run later; their results are only available inside the callback.
  • setTimeout runs once and setInterval repeats; cancel them with clearTimeout/clearInterval.
  • Prefer a recursive setTimeout when runs must not overlap or the delay should change.
  • Node.js callbacks are error-first: check err before using the result; nested callbacks lead to callback hell.
  • Use node:timers/promises with await, AbortController for cancellation, and polling helpers (or Playwright’s expect.poll) for waiting.

Next, continue with Lesson 48: Promises.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in