Networking, Timers and UI Events

Match asynchronous tools to real school tasks

A school app loads a report from a server, schedules a reminder and reacts to a student selection. These tasks finish for different reasons and need different completion rules.

Asynchronous APIs are useful when completion depends on networking, a timer or an external event. Choose the API by the task and design loading, failure, cancellation and out-of-date results deliberately.

  1. Choose an API

    Separate network requests, timer tasks and repeated events.

  2. Trace a reminder

    Explain why zero-delay timers still run later.

  3. Prevent stale updates

    Keep an older report from replacing the currently selected student.

Different triggers require different contracts

  1. Network response

    One request may succeed or fail.

    Report data
  2. Timer threshold

    The callback becomes eligible later.

    Reminder
  3. User event

    Handle each supported selection.

    Selected student
Read these stages alongside the complete example. They explain the relationship; they do not execute code.

A timer, a request and a click are not interchangeable

A network request can fail or return an unsuccessful HTTP status. A timer schedules eligible work after a delay; it does not guarantee execution at an exact instant. An event handler can run repeatedly rather than settle once.

The first executable example uses a local timer, not a network or browser click. Real fetch and DOM event examples require an environment and a real service or element; their outputs cannot be guaranteed from this local lesson alone.

Before starting, review awaited completion and failure. These examples use JavaScript; other languages can use different syntax and rules.

Schedule a reminder without delaying the next statement

setTimeout registers later work. Other work prints during the current synchronous sequence, then Reminder prints when its timer task runs.

The delay is zero only to keep this demonstration quick. It does not mean the callback executes during the registration call.

JavaScript · local teaching example

console.log("Request reminder");
setTimeout(() => console.log("Reminder"), 0);
console.log("Other work");

Expected output

Request reminder
Other work
Reminder

Cancel a pending reminder explicitly

clearTimeout uses the timer handle to cancel this timer before it runs. The Cancelled message is the only output. Cancellation belongs to this timer API; an arbitrary promise has no equivalent universal cancel method.

JavaScript · local teaching example

const timer = setTimeout(() => console.log("Reminder"), 0);
clearTimeout(timer);
console.log("Cancelled");

Expected output

Cancelled

Keep an older completion from replacing a new selection

This local scheduling model starts a request for Maya, then switches the selection to Ravi before the first handler runs. Each request remembers its own version.

The Maya result sees that its version is outdated and does not display. The Ravi result matches the latest version and displays. Real networking still needs error handling and any supported cancellation; this version check prevents an outdated UI update, not the request itself.

JavaScript · local teaching example

let latestVersion = 0;
function requestReport(name) {
  const version = ++latestVersion;
  Promise.resolve(name).then(result => {
    if (version !== latestVersion) return;
    console.log("Display " + result);
  });
}
requestReport("Maya");
requestReport("Ravi");

Expected output

Display Ravi

Apply the rule to a small change

Schedule a local reminder and immediately print Saved. Explain which output comes first.

Worked answer

Saved comes first because the synchronous sequence continues after scheduling. Reminder comes later. A short timer is suitable for demonstrating scheduling, not for guaranteeing a precise school deadline.

JavaScript · local teaching example

setTimeout(() => console.log("Reminder"), 0);
console.log("Saved");

Expected output

Saved
Reminder

Recognize mistakes and limits

For real fetch calls, check response.ok before assuming an HTTP response means success, then handle errors while decoding the body. A network rejection and a server error status are different failure paths.

Use AbortController with operations that support it when a request should be aborted. A Promise.race timeout can stop waiting without stopping the underlying operation; plan cleanup explicitly.

Register event handlers once at the appropriate lifecycle point and remove obsolete listeners. Repeated registration can create duplicate actions. For rapidly changing selections, validate that completion still belongs to the current selection.

For the language or tool rules used here, see JavaScript promise chaining and timing.

Check the core idea

Why is a zero-delay timer unsuitable for an exact execution-time guarantee?
Choose one answer. You can try again.

Answer and explanation

The callback waits for an eligible task turn and can be delayed by other work.

Correct. A delay threshold is not a precise execution appointment.

Apply the idea to a new situation

JavaScript · code for this question

let latestVersion = 0;
function requestReport(name) {
  const version = ++latestVersion;
  Promise.resolve(name).then(result => {
    if (version !== latestVersion) return;
    console.log("Display " + result);
  });
}
requestReport("Maya");
requestReport("Ravi");
What does the version check in the local report model prevent?
Choose one answer. You can try again.

Answer and explanation

An older completed report replacing the newer selected report.

Correct. Only the latest version displays.

Design completion around the task and the current user choice

Networking, timers and events have different contracts. Handle failure, cancel only through supported APIs and prevent obsolete completions from updating the current interface.

Connect this idea with timer and promise ordering and different failure categories.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Write Code People Can Read →