Tips for ending a setInterval loop

I have created a setInterval function in JavaScript to switch the color of a div by applying different CSS classes. Initially, I trigger this color change by pressing a button. However, I am also trying to stop the color transition using the same button but it's not working as expected. Below is my JS code:

    var bsstyles = ["alert alert-success","alert alert-info","alert alert-warning","alert alert-danger"];

    var i = 0;

    var buttonstate = false;

    var runner;

    var mainfun = function () {
        if (buttonstate === false) {
            buttonstate = true;
            document.getElementById("changebutton").className = "btn btn-primary btn-lg active";
            var runner = setInterval(function() {
                document.getElementById("alertw").className = bsstyles[i];
                i++;
                if (i == bsstyles.length) {
                        i = 0;
                }
            },1000);
        } else {
            clearInterval(runner);
            document.getElementById("changebutton").className = "btn btn-primary btn-lg";
            buttonstate = false;
        }
    }

    var changeButton = document.getElementById("changebutton");

    changeButton.addEventListener('click',mainfun,false);

Check out the JSFiddle here

Answer №1

make sure to exclude the var keyword before 'runner' while defining mainfun

using the var keyword creates a new local variable instead of referencing the global variable runner

the corrected code should appear like this

var bsstyles = ["alert alert-success","alert alert-info","alert alert-warning","alert alert-danger"];

var i = 0;

var buttonstate = false;

var runner; // remove var here

var mainfun = function () {
    if (buttonstate == 0) {
        buttonstate = true;
        document.getElementById("changebutton").className = "btn btn-primary btn-lg active";
        runner = setInterval(function() {
            document.getElementById("alertw").className = bsstyles[i];
            i++;
            if (i==bsstyles.length) {
                    i=0;
            }
        },1000);
    } else {
        clearInterval(runner);
        document.getElementById("changebutton").className = "btn btn-primary btn-lg";
        buttonstate = false;
    }
}

var changeButton = document.getElementById("changebutton");

changeButton.addEventListener('click',mainfun,false);

Answer №2

One approach I often take is to save Interval handles directly on the function itself, especially when there will only be one instance:

myFunction.timer = setInterval(function () {
    //Code here
}, 1000);
clearInterval( myFunction.timer );

This method helps avoid having a global variable like 'timer' that could accidentally be overwritten. Although myFunction.timer can still be accessed globally, it's less likely to be modified inadvertently.

Answer №3

Although it has been mentioned before by other responders, the key issue lies in overwriting a global variable with a local one. Here's a simplified version of your code:

let runner = null;
let i = 0;

const changeClassById = (id, className) => {
    document.getElementById(id).className = className;
};

const mainFunction = () => {
    if (runner) {
        clearInterval(runner);
        changeClassById("changebutton", "btn btn-primary btn-lg");
        runner = null;
    } else {
        changeClassById("changebutton", "btn btn-primary btn-lg active");
        runner = setInterval(() => {
            changeClassById("alertw", bsstyles[++i % bsstyles.length]);
        }, 1000);
    }
}

Reducing the number of lines of code reduces the likelihood of errors.

Answer №5

You have mistakenly redefined the interval runner variable; Simply delete 'var' from this line

runner = setInterval(function() {

Check out this link for more information: http://jsfiddle.net/g6to2gqn/4/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unprocessed Promise Rejection Alert: The function res.status is not recognized as a valid function (NEXT JS)

When I console.log(response), I see the result in the terminal. However, when I use res.status(200).json(response), I encounter an error in my Next.js project: Not Found in the browser. router.get("/api/backendData", async (req, res) => { dbConne ...

How can state values be transferred between components?

I have come across various answers on different platforms but haven't been able to achieve the desired results. That's why I am reaching out with this question. So, my question is related to 3 files named: App.js, SignUp.js, and Welcome.js. My ...

Stopping an HTML5 range input at a specific number: Tips and tricks

Does anyone have suggestions on how to use angularjs to stop a range slider at 75? I attempted it but it doesn't seem like the best approach. Any guidance would be appreciated. [EDIT for clarification after max=75 answer] Just to clarify, I want to di ...

The attempt to compress the code in the file from './node_modules/num2persian' using num2persian was unsuccessful

I have been using the num2persian library to convert numbers into Persian characters. However, whenever I run the command npm run build, I encounter the following error: An error occurred while trying to minimize the code in this file: ./node_modules/num ...

Patience is key for a fully completed JSON in JavaScript

I recently came across a similar discussion on Stack Overflow, but it involved using JQuery which I'm not using. My issue is that I need to ensure my JSON data is fully loaded before calling my function. I understand the concept of using a callback, ...

Is there a way for me to connect to my Firebase Realtime Database using my Firebase Cloud Function?

My current challenge involves retrieving the list of users in my database when a specific field is updated. I aim to modify the scores of players based on the structure outlined below: The Realtime Database Schema: { "users": { &quo ...

Position the div so that it is aligned with the top offset of another element

My question is straightforward. I have a div1 element with a variable offset().top that adjusts based on other elements on the page. I am looking to add an absolutely positioned div next to it, which should have the same absolute top value. This can be ach ...

Is there a way to manipulate text in JQuery without altering the inner element?

I am struggling with an issue in my HTML code. Currently, I have the following structure: <h3 id="price">0.00<sup id="category">N/A</sup></h3> My intention is to use AJAX to replace the content within the <h3 ...

Include specific javascript files only for smartphones

Recently, I encountered an issue with a JavaScript code that swaps background images on scroll down. To address the problem with debounce, I ended up setting different debounce times for various browsers (I am aware this is not the ideal solution, but it&a ...

Reverse key-value pairs within a nested object using JavaScript

There is a specific object that I am working with: { "images": [ { "key": "ASDV1-01.jpg", "image_location": "image1.jpg", "data": { "documentid": "CE ...

"Is there a specific way to designate the content type as multipart form data when using Axios

I am experiencing difficulty with axios as I am unable to set the content type to multipart/form-data. Below is the code snippet: function (config) { // Do something before request is sent const isLogin = authService.isLogin(); if (isLogin) ...

Issues with user-generated input not properly functioning within a react form hook

After following the example provided here, I created a custom input component: Input.tsx import React from "react"; export default function Input({label, name, onChange, onBlur, ref}:any) { return ( <> <label htmlF ...

Issue encountered while managing login error messages: http://localhost:3000/auth/login net::ERR_ABORTED 405 (Method Not Allowed)

I am working on the /app/auth/login/route.ts file. import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs' import { cookies } from 'next/headers' import { NextResponse } from 'next/server' export async functi ...

There is a random section that keeps crashing on the website

I have encountered a bug on my one-page Bootstrap template website. One of the sections is causing issues after multiple page refreshes. Despite checking the console for errors, I am unable to identify the source of the problem. Here is the HTML code for ...

Having trouble with your Discord.js Bot continuously going offline and getting Value errors? Here’s how to resolve it

Why do I keep encountering this error? TypeError: Cannot read property 'size' of undefined at Client.client.on.message (/home/colter/Code/groundskeeper/index.js:38:30) at emitOne (events.js:116:13) at Client.emit (events.js:211:7) at MessageCre ...

Converting a string date format to UTC: A step-by-step guide

In my Typescript code, I am trying to convert a date/time format from string to UTC format but currently facing an issue with it. The desired output is as follows: 2018/10/27+16:00 => 20181027T01000Z import * as moment from 'moment' dates=$ ...

Recommendations for a UI library specializing in displaying analytical graphs

Looking to create analytical graphs of tweets similar to the site found at the following link Website-Link Curious about the top open source options available for this task? I've heard good things about Raphael.js. Any other recommendations? ...

extracting web content with selenium and javascript integration

Struggling to extract JavaScript content from a website with selenium and geckodriver, but coming up empty-handed. Below is the snippet of JavaScript code: <div _ngcontent-c2="" class="header-wrapper"> <div _ngcontent-c2="" class="title">S ...

Guide to displaying a spherical grid helper in Three JS

Currently, I am immersed in a fascinating project that involves the movement of small objects and displaying them within a 360-degree image using the ThreeJS library. To achieve this, I am utilizing the concept of a Spherical coordinate system within a sph ...

What is the best way to add JSON data received from an AJAX response to multiple classes?

Currently, I am honing my skills in jquery and have hit a bump in the road. I am receiving JSON data from a fantasy football API and am trying to map over the data to assign each team owner and name to their own div. My main query revolves around how I can ...