-->

JavaScript - Window - The Browser Object Model Part 5: Timers and Intervals

The window object provides methods to execute code after a delay or at regular intervals.

Examples and Explanation

setTimeout()

setTimeout(() => console.log("Executed after 3 seconds"), 3000);

Explanation: Executes a function after a specified delay.

setInterval()

const intervalId = setInterval(() => console.log("Repeating every 2 seconds"), 2000);

Explanation: Executes a function repeatedly at fixed intervals.

clearTimeout() and clearInterval()

const timeoutId = setTimeout(() => console.log("Will not execute"), 5000);

clearTimeout(timeoutId);

clearInterval(intervalId);

Explanation: Stops the execution of functions scheduled with setTimeout or setInterval.

Conclusion

The window object and the Browser Object Model provide essential tools for interacting with and manipulating the browser environment. From handling user inputs with alerts, navigating the browser history, responding to events, and managing timers, mastering the BOM allows developers to create more dynamic and interactive web applications. By leveraging the window object effectively, you can enhance the user experience and add functionality to your web projects.