Scalable Business for Startups

Get the oars in the water and start rowing. Execution is the single biggest factor in achievement so the faster and better your execution.

+91 9472774549 thebytemind@gmail.com Looking for collaboration for your next creative project?

Chapter 14: JavaScript Timers

JavaScript provides several methods for working with timers, enabling developers to create time-based behaviors in web applications. This chapter will cover the core timer functions, their usage, and advanced applications.

14.1 Introduction to Timers

In JavaScript, you can create timers using two primary functions:

  • setTimeout(): Executes a function after a specified delay.
  • setInterval(): Repeatedly executes a function at specified intervals.

Additionally, there are corresponding functions for clearing timers:

  • clearTimeout(): Cancels a timeout set with setTimeout().
  • clearInterval(): Cancels an interval set with setInterval().
14.2 Using setTimeout()

The setTimeout() function takes two parameters: a callback function and a delay (in milliseconds). After the delay, the specified function is executed once.

Syntax:

setTimeout(function, delay);

Example: Basic Usage of setTimeout()
console.log("Start");
setTimeout(() => {
    console.log("Executed after 3 seconds");
}, 3000);
console.log("End");

Output:

Start
End
Executed after 3 seconds

Explanation: The setTimeout() function schedules a callback to run after a 3-second delay, allowing other code to run in the meantime.

14.3 Using setInterval()

The setInterval() function is similar to setTimeout(), but it repeats the execution of the specified function at regular intervals until cleared.

Syntax:

setInterval(function, interval);

Example: Basic Usage of setInterval()
let count = 0;
const intervalId = setInterval(() => {
    count++;
    console.log(`Count: ${count}`);
    
    if (count === 5) {
        clearInterval(intervalId);
        console.log("Interval cleared");
    }
}, 1000);

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Interval cleared

Explanation: The interval function logs the count every second, and after reaching 5, it clears the interval using clearInterval().

14.4 Advanced Timer Techniques
14.4.1 Chaining setTimeout()

You can chain setTimeout() calls to create complex timed sequences.

Example: Chained Timeouts
console.log("Starting sequence");
setTimeout(() => {
    console.log("Step 1 completed");
    
    setTimeout(() => {
        console.log("Step 2 completed");
        
        setTimeout(() => {
            console.log("Step 3 completed");
        }, 1000);
    }, 1000);
}, 1000);

Output:

Starting sequence
Step 1 completed
Step 2 completed
Step 3 completed
14.4.2 Using this with Timers

When using timers within object methods, the value of this can change. To retain the correct context, you can use arrow functions or bind the context.

Example: Retaining this Context
const timerObject = {
    count: 0,
    startTimer() {
        setInterval(() => {
            this.count++;
            console.log(`Count: ${this.count}`);
            if (this.count === 5) {
                clearInterval(this.intervalId);
                console.log("Timer stopped");
            }
        }, 1000);
    }
};

timerObject.startTimer();
14.5 Debouncing and Throttling

In many scenarios, particularly with user input events (like scrolling or resizing), you might want to limit how often a function is called. This is where debouncing and throttling techniques come in handy.

14.5.1 Debouncing

Debouncing ensures that a function is only executed after a certain amount of time has passed since it was last invoked.

Example: Debouncing Input Events
function debounce(func, delay) {
    let timeoutId;
    return function(...args) {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => {
            func.apply(this, args);
        }, delay);
    };
}

const processChange = debounce(() => {
    console.log("Input processed");
}, 500);

document.getElementById("myInput").addEventListener("input", processChange);
14.5.2 Throttling

Throttling ensures a function is called at most once in a specified time interval.

Example: Throttling Scroll Events
function throttle(func, limit) {
    let lastFunc;
    let lastRan;
    return function(...args) {
        if (!lastRan) {
            func.apply(this, args);
            lastRan = Date.now();
        } else {
            clearTimeout(lastFunc);
            lastFunc = setTimeout(() => {
                if (Date.now() - lastRan >= limit) {
                    func.apply(this, args);
                    lastRan = Date.now();
                }
            }, limit - (Date.now() - lastRan));
        }
    };
}

const logScroll = throttle(() => {
    console.log("Scroll event logged");
}, 1000);

window.addEventListener("scroll", logScroll);
14.6 Summary

JavaScript timers (setTimeout() and setInterval()) are powerful tools for creating time-based behavior in web applications. Understanding how to use them effectively, along with techniques like debouncing and throttling, can significantly enhance user experience by controlling event handling and improving performance.

14.7 Exercises
  • Create a countdown timer that counts down from 10 to 0 and displays an alert when it reaches zero.
  • Implement a simple stopwatch that starts, stops, and resets on button clicks.
  • Develop a feature that auto-saves a form every 5 seconds as the user types.