How to Start and Stop a setInterval Call in JavaScript?

If you are wondering how to start and stop a setInterval call in JavaScript? Read on to explore new insights!

In this article, we will show you how to use the setInterval and clearInterval ()methods in JavaScript to start and stop a function at a specified time interval.

We will provide a detailed explanation of the syntax, parameters, and return value of these methods, as well as examples of how to use them in practice.

What is setinterval in JavaScript?

The setInterval() is a method in JavaScript that allows you to repeatedly execute a function or a block of code at a specified time interval.

This method returns an ID that can be used to stop the interval using the clearInterval() method.

The first argument of setInterval() is the function or code to be executed, and the second argument is the time interval in milliseconds between each execution.

The interval will continue until clearInterval() is called or the window is closed.

Syntax

setInterval(function, delay, [arg1, arg2, ...]); ✅

Parameter

function (Required)

The function to be executed every delay milliseconds.

delay (Required)

The time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function or code.

arg1, arg2, …(Optional)

Additional parameters to pass to the function specified by callback.

Return value

The setInterval() method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval() and passing it the ID value returned by setInterval().

How to stop a setInterval call in JavaScript using clearInterval () method?

To stop a setInterval() call in JavaScript, you can use the clearInterval() method. The setInterval() method returns an ID value that represents the interval object.

You can pass this ID value as an argument to the clearInterval() method to stop the interval.

Here’s an example:

let intervalID = setInterval(() => {
console.log('Hi welcome to Itsourcecode!');
}, 1000);

setTimeout(() => {
clearInterval(intervalID);
}, 5000);

Output:

Hi welcome to Itsourcecode!
Hi welcome to Itsourcecode!
Hi welcome to Itsourcecode!
Hi welcome to Itsourcecode!

In this example, the setInterval() method is used to log ‘Hi welcome to Itsourcecode!‘ to the console every 1000 milliseconds (1 second).

The ID value returned by setInterval() is stored in the variable intervalID. After 5000 milliseconds (5 seconds), the setTimeout() method is used to call the clearInterval() method and pass it the intervalID value.

This stops the interval and the ‘Hi welcome to Itsourcecode!‘ message is no longer logged to the console

How to start and stop a setInterval call in JavaScript?

In JavaScript, you can use the setInterval function to repeatedly call a function at a specified time interval.

The setInterval function returns an ID value that you can use to stop the interval using the clearInterval function.

Here’s the complete example code:

<html>
<style>

            body {

                text-align: center;
            }

        </style>
    <body>
        <h2>How to Start and Stop a setInterval Call in JavaScript? </h2>
        <p id="demo"></p>
        <button onclick="myStartFunction()">Start time</button>
        <button onclick="myStopFunction()">Stop time</button>
    </body>
    <script>
var sampleVar;
function sampleTime() {
    var date = new Date();
    var time = date.toLocaleTimeString();
    document.getElementById("demo").innerHTML = time;
}
function myStartFunction() {
    sampleVar = setInterval(sampleTime, 100); ✅
}

function myStopFunction() {
    clearInterval(sampleVar);
}

 </script>

</html>

The example code above, defines several variables and functions. The myVar variable is used to store the ID value returned by the setInterval function.

The sampleTime function creates a new Date object, gets the current time as a string using the toLocaleTimeString method, and sets the innerHTML property of the element with ID “demo” to the current time.

The myStartFunction function is called when the “Start time” button is clicked. It calls the setInterval function with the sampleTime function and an interval of 100 milliseconds as arguments, and stores the ID value returned by setInterval in the sampleVar variable.

This starts an interval that calls the sampleTime function every 100 milliseconds, updating the time displayed on the page.

The myStopFunction function is called when the “Stop time” button is clicked. It calls the clearInterval function with the ID value stored in the sampleVar variable as an argument.

This stops the interval that was started by the setInterval call in the myStartFunction, stopping the updates to the time displayed on the page.

Output

Conclusion

The setInterval and clearInterval methods in JavaScript provide a powerful way to execute a function or block of code at specified time intervals.

The setInterval method starts the execution and returns an ID that can be used to stop the execution using the clearInterval method.

We have also provided example code that demonstrates how to use these methods to start and stop a clock.

Remember, it’s important to always clear your intervals when they’re no longer needed to prevent unnecessary resource usage.

We hope this article has provided you with enough information to help you understand the stop setinterval in JavaScript.

If you want to dive into more JavaScript topics, check out the following articles:

Thank you for reading Itsourcecoders 😊.

Frequently Asked Questions

Is JavaScript still worth learning in 2026?
Yes. JavaScript runs on 98% of websites for the front-end, dominates the back-end via Node.js, powers mobile apps through React Native, builds desktop tools through Electron, and is the scripting layer for most AI tooling (LangChain.js, OpenAI SDK, Vercel AI). Whether you target web, mobile, AI, or full-stack capstones, JavaScript is the broadest single language you can learn.
What is the difference between var, let, and const?
var is function-scoped, hoisted to the top of its scope, and can be redeclared, which leads to bugs in modern code. let is block-scoped (only visible inside the nearest {}) and can be reassigned. const is block-scoped and cannot be reassigned, although object contents can still mutate. Default to const for everything, switch to let only when you actually need to reassign, and avoid var in any code written after 2017.
Which JavaScript version should I target in 2026?
Target ES2020 (ES11) as the safe baseline because every modern browser and Node.js 14+ supports it fully. ES2022 adds useful features like top-level await, private class fields with the # prefix, and the .at() array method. If you are writing for older browsers (IE11 or older Android WebViews), transpile down with Babel or use a build tool like Vite, esbuild, or webpack.
What is the best free editor for JavaScript?
Visual Studio Code is the industry standard, free, with built-in IntelliSense, debugger, terminal, Git, and a huge extension marketplace (ESLint, Prettier, GitHub Copilot, Tailwind). Install the JavaScript and TypeScript Nightly extension for the latest language features. JetBrains WebStorm is more powerful and free for students with a verified .edu email. For quick scratchpad work, the Chrome DevTools Sources panel includes a workspace and breakpoint debugger.
How do I run JavaScript locally vs in the browser?
In the browser: open DevTools with F12 (or right-click then Inspect), go to the Console tab, type or paste your code, press Enter. For HTML pages, add a script tag pointing to your .js file. Locally with Node.js: download Node from nodejs.org (LTS version), then run node script.js in your terminal from the file folder. Use the same Node setup for backend capstones, API integrations, and scripts that do not need a browser.
What can I build with JavaScript for my BSIT capstone?
Common BSIT capstones in JavaScript: full-stack web apps using React or Vue on the front-end with Node.js and Express on the back-end (MongoDB or MySQL for the database), real-time chat or notification systems using Socket.io, single-page dashboards with Chart.js or D3.js, cross-platform mobile apps with React Native, AI-powered chatbots using OpenAI SDK and LangChain.js, and Chrome extensions for productivity tools. Add Tailwind CSS for the UI and Vercel or Netlify for free deployment.

Caren Bautista


Technical Writer at PIES IT Solution

Responsible for crafting clear, well-structured, and beginner-friendly content across the platform. Handles the writing, proofreading, and editorial review of tutorials, guides, and documentation to ensure every article is accurate, readable, and easy to follow.

Expertise: Technical Writing · Content Creation · Documentation · Editorial Writing · JavaScript · TypeScript · Python · Python Errors · HTTP Errors · MS Excel
 · View all posts by Caren Bautista →

Leave a Comment