JavaScript's setTimeout function seems to be executing an excessive number of times

After creating a loop with the setTimeout function, I encountered an issue where it would call itself after the 2nd or 3rd step because it started executing twice simultaneously. Here is how my function looks:

var value = 70, 
    intervalID = null;

function interval() {
  intervalID = setTimeout(countDown, 1000);
}

function countDown() {
  value--;
  if(value > 0) {
    clearTimeout(intervalID);
    interval();
  } else {
    endInterval();
  }
}

function endInterval() {
  // do something
}

If I console.log the variable 'value', it shows 69 and then 68, but afterwards it starts decreasing twice in one function call. I only call the function 'countDown()' from one place.

What could be causing this issue?

Edit: The code is now functioning properly.

Answer №1

My suggestion would be to "sanitise" the timeouts by halting the previous one.

function interval() {
  clearInterval(intervalID);
  intervalID = setTimeout(countDown, 1000);
}

Though it appears to be managing symptoms rather than addressing the root cause of the problem. It might be more beneficial to identify the underlying issue.

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

Calculating the vertical distance between an element and the top of the page

I am attempting to calculate the distance between the top of an element and the top of the page every time the user scrolls. Although I have managed to make it work, the issue arises when scrolling - the distance remains unchanged. I tried addressing this ...

Tips for displaying lower quality images while initially downloading higher quality versions

I need to download and display a large image in an img tag. Since the image is not Progressive JPEG, it will render as it downloads. Is there a way to show a low-resolution version of the image while it fetches from the server using only CSS or an HTML p ...

Executing javascript href using Python in Selenium

Currently, I am attempting to use Selenium in Python to click on a href JavaScript link. The HTML code appears as follows: HTML Example and my goal is to click on javascript:goType(1). This is the approach I have taken: advance_search = browser.find_el ...

Tips on creating a subsequent post for a file that has been uploaded to a Node Express server and then forwarded to a different API

We are currently working with an Express server in Node, where we upload a file on one route and then need to send this file to another endpoint for processing. However, the file is not stored locally on the server; it exists as an uploaded object. I&apos ...

How come executing a function in the Node.js REPL using )( actually functions?

In JavaScript, why is it possible to call a function like this when tested with node.js: ~$ node > function hi() { console.log("Hello, World!"); }; undefined > hi [Function: hi] > hi() Hello, World! undefined > hi)( // Why does this work? Hell ...

Issue with loading CSS and JavaScript following a GET request

I initially used express and the render function to display different pages on my website. However, I've now decided to switch to vanilla JavaScript instead. The objective is to load the HTML file along with all the necessary JS and CSS files. Below i ...

Dynamically loading an AngularJS controller

I am faced with the challenge of integrating an Angular app with dynamically loaded controllers into an existing webpage. Below is a code snippet where I have attempted to achieve this based on my understanding of the API and some research: // Create mod ...

An unexpected JavaScript error has occurred in the main process: TypeError - not enough arguments provided

During my attempt to package an electron project using the electron-packager npm module, I encountered an error when running the .exe file of the packaged product. The error specifically references app/dist/packaged-app-win32-x64... and you can see the err ...

Incorporate a dynamic PowerPoint presentation directly onto my website

In my situation, on the client side, users can select image files (jpg|png|gif), PDF files, and PPT files which are then stored in a database. When viewing these selected files in the admin panel, I am using conditional statements to display them appropr ...

Vue.js not responding to "mousedown.left" event listener

I am trying to assign different functionalities to right and left click on my custom element. Within the original code, I have set up event listeners for mouse clicks in the element file: container.addEventListener("mousedown", startDrag); conta ...

Updating the iFrame source using jQuery depending on the selection from a dropdown menu

I want to create a dynamic photosphere display within a div, where the source is determined by a selection from a drop-down menu. The select menu will provide options for different rooms that the user can view, and the div will contain an iframe to showca ...

The hovering event trail feature is not functioning in tsParticles, unlike in particlejs

I have two questions regarding the implementation of tsParticles in my React application. First question: <Particles id="tsparticles" options={{ background: { color: { value: "black&quo ...

Creative ways to use images as borders with CSS in React JS

import React, { Component } from 'react'; class BigText extends Component { constructor(props) { super(props); this.state = { title: '', text: '', summary: '' ...

Struggling to configure an onClick handler in Next.js

Unexpectedly, I was met with a surprise while trying to access react.dev, as it stated that create-react-app is no longer recommended for bootstrapping React applications. No worries, the world is always evolving. Let's explore Next.js for my first p ...

Switching out one block of HTML with another in JavaScript is a powerful way to dynamically update

I am working on creating a feature on a webpage where clicking a button will change the HTML code inside a specific div. Essentially, I want to be able to update the content of a div by simply clicking a link. Here are two different sets of HTML code: Co ...

Is SPE.Group.tick experiencing issues with a faulty delta argument in Three.js / ShaderParticleEngine?

I recently started using the ShaderParticleEngine library in Three.js to set up particle emitters. After browsing through various code snippets online, I managed to get an emitter up and running. Initially, I thought it wasn't working as I could only ...

Is it acceptable to employ async: false when requesting small amounts of data?

I am curious about the best practices for retrieving small data from the server. One example is using an ajax (or sjax) call to check for new notifications for a user. function checkNewNotifs() { $.ajax({ url: '/Home/CheckNewN ...

React-Select for Creating a Dynamic Multi-Category Dropdown Menu

I am looking to incorporate react-select into my project for a multi-category dropdown list. Specifically, I need the ability to select only one option at most from each category. To better illustrate this requirement, consider the following example wher ...

Dealing with a 409 conflict situation involving a document in Node.js using Nano library

After conducting research, it has come to my attention that there are numerous document conflicts with couchdb. While exploring a potential solution in Updating a CouchDB document in nano, I discovered the following steps: Retrieve the document Store th ...

Error: The function is not defined on this.props during the handleCHange event

After going through numerous answers to similar questions on this topic, I believe that I am following all the necessary steps but for some reason, it is not working. Below is the specific section of code that is causing the error: import React from &apos ...