Skip to the content.

Prepared Based on: MAD 2 JavaScript week-3 Open Session

Target Audience: Beginners with Python background and Javascript basic understanding

Prepared by: Shri Krishna 

Last term live session for reference: Mad-2 week-3 open session

May term live session taken based on this doc: Mad-2 week-3 open session


JavaScript Callback Functions and Timers

Callback functions are fundamental in JavaScript. A callback is simply a function passed as an argument into another function, so that it can be “called back” (invoked) later. In other words, the receiving function can execute the callback at the appropriate time to complete some task. Callbacks can run synchronously (immediately) or asynchronously (later, after some operation completes).

For example, many array methods like forEach and map accept callbacks, and asynchronous APIs like setTimeout() or fetch().then() use callbacks when operations finish.

setTimeout

The setTimeout() function schedules a one-time callback after a specified delay (in milliseconds). Its basic behavior is: “set a timer, and when it expires, run the given function”.

For example, setTimeout(fn, 1000) will call fn after ~1000ms. Because it’s asynchronous, code after setTimeout continues running immediately – it does not pause the script. The function returns a timer ID (a number) which can be used to cancel the timeout before it fires.

setInterval

The setInterval() function repeatedly runs a callback at fixed time intervals. You pass it a function and a delay, and it will call that function every delay milliseconds until you stop it. Like setTimeout, it returns an interval ID that you can later use to clear the interval.

clearTimeout

The clearTimeout() function stops a timeout scheduled by setTimeout(). You pass it the timer ID that setTimeout returned. If that timeout hasn’t fired yet, it gets cancelled and will never execute its callback. If you pass an invalid or already-cleared ID, clearTimeout does nothing.

For example, if a user takes an action that makes the delayed callback irrelevant, you can call clearTimeout to prevent it from running.

clearInterval

The clearInterval() function stops a repeating action created by setInterval(). You give it the interval ID returned by setInterval, and it will cancel further executions of that callback. Like clearTimeout, if you pass an invalid ID it simply does nothing.

Best Practices and Common Patterns

Each of these functions is part of standard Web APIs and works in browsers (and Node.js provides similar global functions). They are essential for controlling timing and flow in JavaScript, especially when working with asynchronous operations.

Synchronous vs Asynchronous Programming in JavaScript

Synchronous code runs one step at a time, in order. Each operation must finish before the next one starts. In other words, the program “steps through” each line sequentially, waiting on each to complete. For example:

console.log("Step 1");
console.log("Step 2");
console.log("Step 3");
// Output: Step 1, then Step 2, then Step 3 (in order)

In this code, each console.log waits for the previous one to finish before running. This sequential flow is simple and predictable, but if one step takes a long time (like loading a large file), it blocks everything else from running.

Asynchronous code, by contrast, allows tasks to be started and then run independently. In asynchronous execution, you can initiate a long-running task and then move on to other work before that task finishes. The long task runs “in the background,” and when it’s done your code is notified (often via a callback). This non-blocking behavior keeps applications responsive. For example:

console.log("Hi");

setTimeout(() => {
  console.log("Geek");
}, 2000);

console.log("End");
// Output: Hi, then End, then (after 2 seconds) Geek

In the above code, “Hi” and “End” are logged immediately, before the delayed “Geek” message. That’s because setTimeout is asynchronous: it hands off the callback to the browser’s timer system and immediately continues to the next lines. Only after 2000 ms does the callback run. This shows how asynchronous functions like setTimeout don’t block the main flow.

Real-World Analogies

These analogies illustrate how synchronous tasks block the flow (one at a time), whereas asynchronous tasks can overlap and improve efficiency.

Synchronous vs Asynchronous: Key Points

Code Examples

Synchronous example: Each line runs one after another:

console.log("A");
console.log("B");
console.log("C");
// Output: A, then B, then C (in order)

Asynchronous example with setTimeout:

console.log("Start");
setTimeout(() => {
  console.log("Inside timeout");
}, 1000);
console.log("Finish");
// Output: Start, then Finish, then (after ~1 second) Inside timeout

Here, “Finish” appears before “Inside timeout” even though the setTimeout call comes before it. That’s because the timer callback is deferred.

Using Callbacks: A callback is just a function you pass to another function to run later. For example, with setTimeout we give a callback to execute after a delay. Callbacks let you specify what to do when an async operation finishes. For instance:

console.log("Before fetch");
setTimeout(() => {
  console.log("Data fetched!");
}, 2000);
console.log("After fetch");
// Output: Before fetch, After fetch, then (after 2s) Data fetched!

This shows that the code after setTimeout runs immediately; only later does the callback run, thanks to the event loop.

Asynchronous Features: setTimeout, setInterval, and Callbacks

Because of these async features, code can be non-sequential. You might see the end of a function run before a callback or timer fires. This is normal: JavaScript is single-threaded but uses its event loop to handle async tasks without stopping the main thread.

In summary: Synchronous JavaScript does things in order, blocking each step (like a single queue). Asynchronous JavaScript starts tasks that run in the background and continues with other work, which keeps apps responsive. Timers (setTimeout, setInterval) and callbacks are core to this – they let you schedule code to run later without freezing the current flow.

Sources: Authoritative JavaScript docs and tutorials.

Vue.js Examples and Setup

Below is an HTML example for Vue 2 and Vue 3 that implements the given component (showing “Waiting…” and then “Hello from Vue!” after 2 seconds). The examples use a CDN script so you can simply open the HTML file in a browser to run it. We then discuss the differences between Vue 2 vs Vue 3 (including renamed lifecycle hooks and API changes) and the various ways to run Vue (CDN, CLI, or Vite).

Vue 2 Example (with CDN)

In Vue 2, you include the Vue 2.x script via a <script> tag, and then create a Vue instance with new Vue(...). For example:


<!-- index.html for Vue 2 -->
<div id="app">
  <!-- Only show the message when visible is true -->
  <p v-if="visible">{{ message }}</p>
</div>

<!-- Include Vue 2 from CDN -->
<script src="https://cdn.jsdelivr.net/npm/vue@2.7.16/dist/vue.js"></script>
<script>
// Create a new Vue 2 instance
new Vue({
  el: '#app',
  data: {
    message: 'Waiting...',
    visible: false,
    timeoutId: null
  },
  mounted() {
    // After 2 seconds, show the message
    this.timeoutId = setTimeout(() => {
      this.visible = true;
      this.message = 'Hello from Vue!';
    }, 2000);
  },
  beforeDestroy() {
    // Clear timer when component is destroyed
    clearTimeout(this.timeoutId);
  }
});
</script>

Vue 3 Example (with CDN)

In Vue 3, the API has changed: you use Vue.createApp() instead of new Vue, and the destroy hooks were renamed. Here is the equivalent example in Vue 3:


<!-- index.html for Vue 3 -->
<div id="app">
  <p v-if="visible">{{ message }}</p>
</div>

<!-- Include Vue 3 from CDN -->
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
// Use the global Vue object to create the app
const { createApp } = Vue;
createApp({
  data() {
    return {
      message: 'Waiting...',
      visible: false,
      timeoutId: null
    };
  },
  mounted() {
    // After 2 seconds, show the message
    this.timeoutId = setTimeout(() => {
      this.visible = true;
      this.message = 'Hello from Vue!';
    }, 2000);
  },
  beforeUnmount() {
    // Clear timer when component is unmounted
    clearTimeout(this.timeoutId);
  }
}).mount('#app');
</script>

Key Differences (Vue 2 vs Vue 3)

Running Vue: CDN vs CLI vs Vite