How can I stop the setinterval function in JavaScript?

My issue revolves around intervals. Upon declaring a function with setInterval, I find that even after clearing the interval, the function continues to execute. Here is my code:

if (score == 1) {
    leftBlinkTimer(0)
 } else if (score == 0) {
    leftBlinkTimer(1)
 }

function leftBlinkTimer (state) {
    let leftBlin = 0;
    var timer;
    if (state == 0) {
        timer = setInterval(() => {
            if (leftBlin == 0) {
                const newData = {
                    stateLeftBlinker: 'rgba(255, 255, 255, 1)'
                }
                vm.changeMicro(newData)
                leftBlin = 1;
            } else if (leftBlin == 1) {
                const newData = {
                    stateLeftBlinker: '#47EC5B'
                }
                vm.changeMicro(newData)
                leftBlin = 0;
            }
        },600)
    } else if (state == 1 || state == '1') {
        clearInterval(timer)
    }

Despite attempting to check the state in the timer and clear it, I've encountered issues where both 0 and 1 lead to the same state. Any assistance would be greatly appreciated! Thank you for your help :) I eagerly await a resolution

Answer №1

Your current issue is connected to how the timer variable is scoped within the function called leftBlinkTimer. The timer variable is localized inside this function, so using clearInterval(timer) will not target the same timer from the previous invocation of leftBlinkTimer.

Moving the declaration outside of the function would resolve this problem.

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

Is it possible to utilize the maximum value from the store in Vuelidate while implementing Vue?

Utilizing VUE and Vuelidate for form input validation, specifically within a modal popup that retrieves data through ...mapGetters from the store. When static values are set like this, it functions correctly : validations: { refundAmount: { ...

Insert icons in the action columns and in every single row

https://i.stack.imgur.com/4EH91.png In the realm of vue.js, there exists a project tailored for a thriving car sales company. The intricacies lie within a table fuelled with essential information concerning each vehicle, evident in the image provided. Ever ...

Intermittent occurrence of (404) Not Found error in the SpreadsheetsService.Query function

Using the Spreadsheet API, I frequently update various sheets. Occasionally, and without any pattern, the SpreadsheetsService.Query function returns a (404) Not Found error. This issue does not seem to be related to internet connectivity or server downti ...

using conditional statements in an app.get() method in express js

app.get('/api/notes/:id', (req, res, next) => { fs.readFile(dataPath, 'utf-8', (err, data) => { if (err) { throw err; } const wholeData = JSON.parse(data); const objects = wholeData.notes; const inputId ...

Is it possible to transfer a massive number of files using node.js?

I need to asynchronously copy a large number of files, about 25000 in total. I am currently using the library found at this link: https://github.com/stephenmathieson/node-cp. Below is the code snippet I am using: for(var i = 0; i < 25000; i++ ...

I am experiencing issues with the functionality of front-page.php on my WordPress website

Seeking guidance in addressing a web development issue: I have encountered a problem with a website that I am currently working on locally using WordPress. I added the following code to the header.php file: <link rel="stylesheet" type="text/css" href= ...

Applying Styles to Cells Using the Google Sheets API (v4)

Having encountered an issue while using the Google Sheets API (v4) for programmatically creating or updating spreadsheets, I have come across the following problem: According to the documentation (https://developers.google.com/sheets/api/reference/rest/v4 ...

Is it possible to use multiple routes in the same page with Vue-router?

In the process of developing a Vue-based web application that utilizes vue-router in history mode, everything was functioning smoothly for navigating between various pages. However, a new request has been made to open certain pages within a virtual dialogu ...

Binding events within other events can be achieved using D3

Trying to implement code from Scott Murray's book "Interactive Data Visualization for the Web" to create versatile bar graphs. Though the code successfully generates and updates graphs, it seems that the sorting functionality is not functioning as exp ...

What's the reason why Angular stops flickering with the use of "/" in href?

Recently, I've come across a peculiar issue in one of my web applications while using Angular's routeProvider as a template engine. The app functions properly, but the behavior seems inexplicable to me. The problem arises during page transitions ...

Vue specifies the location of the index.html file

I'm new to working with Vue and node, and I'm attempting to insert a global value in my project by placing my index.html in a public directory. After creating the project, I noticed that the public src folder was not generated, but I could still ...

Vue's parent-child components interact through asynchronous lifecycles

Even though I'm directed to 'myFavouritePage', the message 'Hi, I'm child' is displayed after the redirection. Is there a parent function that creates the child components upon completion? Parent: beforeCreate () { var or ...

Alter the responseType within Angular (5) once the response has been received

Is it possible to dynamically change the response type in the post method (angular 5) after receiving the response? The challenge: I need the response type to be blob when the response is successful, and json when there's an error. I've searc ...

Sending a POST request using Axios to the 'appName/v1/users/' route (using Djoser) results in a 401 error, whereas Postman does not encounter this issue

As I delve into Django, I am embarking on the task of setting up basic user authentication with a REST API and a Vue.js frontend. The method I am using to send requests is through axios, which is first configured in a separate composable file named axios.j ...

Ways to Identify When the Back Button is Clicked

Currently, I am developing an HTML website that contains 4 divs on the index.html page. Initially, when clicking on a div, it would expand while the other sections reduced in width. However, the client requested that the URL should change when clicking o ...

Issue encountered when calling theme.breakpoints.down('') function from Material UI

As a novice, I have ventured into using material UI on the front-end of my project. My aim is to achieve responsiveness by leveraging theme.breakpoints.down as indicated in the material UI documentation. However, when attempting to implement this, I encoun ...

Instantly magnifying on the initial point regardless of the zoom type chosen is a feature of Chart.js zoom

Despite adding zoom functionality to my line chart, I am facing an issue where it automatically zooms in to the first point and does not allow me to zoom back out, except for using the reset zoom function. The zoom out function is also not working properly ...

Guide on transferring JavaScript Objects from the Front End to Spring Boot Back-end and effectively processing and parsing them

After struggling with this issue repeatedly while developing my web apps, I've reached a breaking point and need some help. My frustration might come across as venting, but I'm genuinely stuck. The challenge I'm facing is sending key-value ...

Error in Discord Bot: discord.js showing TypeError when trying to read the length of an undefined property

I'm currently working on developing a Discord bot and using CodeLyon's Permissions V2 video as a guide for reference. There seems to be an issue in my message.js file which contains the following code: require('dotenv').config(); //cre ...

Set the height of the div to match the length of the downward swipe

I am working on gradually revealing a div as the user swipes down on the body element. Currently, I am using jQuery along with hammer.js to detect the swipe gesture, but I need assistance in determining the distance of the swipe and adjusting the height o ...