Mastering JavaScript Asynchronous Operations (Part 2)

Mastering JavaScript Asynchronous Operations (Part 2)

JavaScript is a versatile and powerful language, especially when it comes to handling asynchronous tasks. In this blog post, we'll explore how to use setTimeout and setInterval functions effectively, and how to control their behavior using buttons in a simple web application.

HTML Structure

First, let's set up a basic HTML structure with two buttons: one to start an interval timer and another to stop it.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Lets learn JavaScript</h1>
    <button id="start">Start</button>
    <button id="stop">Stop</button>
</body>

JavaScript Code

Now, let's dive into the JavaScript code. We will cover several aspects of using setInterval and setTimeout.

Basic setInterval Usage:

The setInterval function repeatedly calls a function or executes a code snippet with a fixed time delay between each call. Here's a simple example:

setInterval(function(){
    console.log("javascript")
}, 1000);

This code logs "javascript" to the console every second (1000 milliseconds).

Passing Function References:

Instead of passing an anonymous function, you can pass a function reference to setInterval.

const sayName = function(){
    console.log("javascript");
}
setInterval(sayName, 1000);

Passing Arguments to the Function:

You can also pass arguments to the function being called by setInterval.

const sayName = function(str){
    console.log(str);
}
const intervalId = setInterval(sayName, 1000, "hello");

This logs "hello" to the console every second.

Stopping the Interval

To stop the interval, use clearInterval and pass the interval ID returned by setInterval.

clearInterval(intervalId);

Controlling the Interval with Buttons:

Let's add event listeners to our start and stop buttons to control the interval timer.

let returnId;
document.querySelector('#start').addEventListener('click', function(){
    returnId = setInterval(sayName, 1000, "hello harsh");
});

document.querySelector('#stop').addEventListener("click", function(){
    clearInterval(returnId);
});

Here, when the start button is clicked, setInterval is called, and the interval ID is stored in returnId. When the stop button is clicked, clearInterval is called with returnId, stopping the interval timer.

Wrap Up

In this post, we've covered the basics of setTimeout and setInterval, how to pass function references and arguments, and how to control the execution using buttons. These are essential tools for handling asynchronous tasks in JavaScript, making your web applications more dynamic and responsive.