Why does the setInterval function only run once before stopping?

Can someone assist me with this issue? The stop button only invokes clearInterval() once - what is causing this problem in the code?

var startButton = document.querySelector("#start");
var stopButton = document.querySelector("#stop");

window.addEventListener('load', () => {

  function runInterval() {
    var time = setInterval(function() {
    console.log("Set interval executed");
  }, 1500);
    return time;
  }

  var time = runInterval();
  
  stopButton.addEventListener("click", function() {   
    clearInterval(time);
  });

  startButton.addEventListener("click", function() {
    runInterval();
  });
});
<button id="stop"> stop! </button>
<button id="start"> start! </button>

Answer №1

It appears that setInterval is being called multiple times, resulting in the activation of several timers simultaneously. To create a more efficient version, consider the following:

let timer;

const begin = () => {
  console.log("initiating...")
  if(!timer) {
    timer = setInterval(
      ()=> {console.log("interval")}
      , 1000)  
  }
}

const halt = () => {
  console.log("stopped")
  clearInterval(timer);
  timer = null; 
}
<button onclick="halt()" id="halt"> halt! </button>
<button onclick="begin()" id="begin"> begin! </button>

Answer №2

Were you aware that the declaration

var time = setInterval(function() {..})
is within the scope of the interval() function? Therefore, its scope is limited to the interval() function.

However, another declaration var tiempo = intervalo() exists outside of the interval function. These two variables, tiempo, are distinct entities. This is why clearInterval(tiempo); does not work as expected.

Why does it work the first time? This is because when the DOM is loaded and the event load is triggered, the code inside the function sets var tiempo = intervalo(), which is only executed once until it is cleared. When clicking on start again, the outside tiempo was not set to anything.

The solution is simple: declare tiempo at the beginning of the load callback and then assign it the returned intervalId from setInterval.

var start = document.querySelector("#start");
var stop = document.querySelector("#stop");

window.addEventListener('load', () => {
  var tiempo;
  function intervalo() {
    //tiempo was declared in this function's closure
    tiempo = setInterval(function() {
    console.log("Set interval executed");
  }, 1500);
  }

  
  stop.addEventListener("click", function() {   
    //tiempo was declared in this function's closure
    clearInterval(tiempo);
  });

  start.addEventListener("click", function() {
    intervalo();
  });
});

p/s: please read more about scope in javascript, especially closure.

Answer №3

It seems like your variable naming is causing confusion as you are constantly overwriting the previous setInterval id with a new one each time. To prevent this scenario, I recommend using a more clear and structured naming convention.

var startButton = document.querySelector("#start");
var stopButton = document.querySelector("#stop");
var intervalReferenceId;
window.addEventListener('load', () => {

  function runInterval() {
    return setInterval(function() {
      console.log("Set interval executed");
    }, 1500);
  }

  intervalReferenceId = runInterval();
  
  stopButton.addEventListener("click", function() {   
    clearInterval(intervalReferenceId);
  });

  startButton.addEventListener("click", function() {
    intervalReferenceId = runInterval();
  });
});
<button id="stop"> Stop! </button>
<button id="start"> Start! </button>

Answer №4

It's important to remember that once you set the variable tiempo, you will need to reset it within your interval function.

var start = document.querySelector("#start");
var stop = document.querySelector("#stop");

window.addEventListener('load', () => {

  function intervalo() {
    return setInterval(function() {
       console.log("Set interval executed");
    }, 1500);
  }
  var timer = true;
  var tiempo = intervalo();
  
  stop.addEventListener("click", function() {   
    clearInterval(tiempo);
    timer = false;
  });

  start.addEventListener("click", function() {
    if(timer == false) {
       tiempo = intervalo();
       timer = true;
    }
  });
});
<button id="stop"> stop! </button>
<button id="start"> start! </button>

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

Enable automatic suggestion in Monaco Editor by utilizing .d.ts files created from jsdoc

I am in the process of creating a website that allows users to write JavaScript code using the Monaco editor. I have developed custom JavaScript libraries for them and want to enable auto-completion for these libraries. The custom libraries are written in ...

Transforming the code from numerous div elements to utilizing Ajax for efficient execution

One of the key functionalities is that the content within the <div> changes based on the option selected in the <select> element. I am looking to incorporate ajax instead of multiple <div> elements. However, my proficiency with ajax is l ...

Angular image source load test encountered an error

<div class="col-xs-4 col-sm-4 col-md-4"> {{jsonData[current].profilepic}} <div ng-if=IsValidImageUrl(jsonData[current].profilepic)> <img id="pic" ng-src="{{jsonData[current].profilepic}}" alt=""/> </div> < ...

What exactly happens behind the scenes when utilizing the React hook useEffect()? Is an effect set up with useEffect able to halt the main thread

According to the documentation for the useEffect() hook in React, it states that: "Effects scheduled with useEffect don’t prevent the browser from updating the screen." Insight Unlike componentDidMount or componentDidUpdate, effects set with ...

Can React provide custom styling to a specific segment of text before displaying it?

I'm looking to create a pokemon search box that offers suggestions of pokemons as the user types. It's working fine so far, but I also want to highlight the searched text when displaying the entire pokemon name. Basically, I want to replace the ...

Function in jQuery to reference two different divs

I'm currently facing an issue with a code snippet that I have. The requirement is for the user to be able to hover over "Div 1" and/or "Div2" and trigger a red border around both elements simultaneously. Due to the complexity of my WordPress theme, th ...

The behavior of the "checked" attribute in VueJS checkboxes does not always match their actual state

In this example, I have created a todo-list with checkboxes that can be checked or unchecked based on whether a task is completed or not. If you uncheck a checkbox in the "Complete tasks" section, the next checkbox will also appear unchecked even if it is ...

Replace a function within a placeholder

Looking to validate the functionality of my custom Google Maps geocoder directive. In my code, I've set up a geocode constructor that I have already partially implemented: ... link: function(scope) { var map, geocoder, myLatLng, ...

Removing the initial 0 from the input

I have a form input field that I want to format using jQuery 1.7.2 <input style="text-align:right;" type="text" name="DiversionCalc_Diversion_Rate" id="calc_dr" value="0.25%" /> My goal is to adjust the formatting when the input field loses focus. ...

What is the best way to incorporate a success function into this?

Is it possible to incorporate success and fail functions into the following code? I'm struggling with how to do it. Here is the code snippet: class ={}; class.hey = function(values) { document.getElementById(values.id).innerHTML = ...

Issue with passing jQuery cookie between two HTTPS pages

I am attempting to transfer a cookie between two secure HTTPS pages using jQuery cookies. The cookie is initially set on page 1 using this code: $.cookie('name', variable, { expires: 300 , secure:true}); Upon navigating to the next page, I try ...

What is the best way to toggle a div and dynamically load content into it while it's open?

I am looking to create a toggle effect where a div opens, loads a page within it, and then can be closed again. My goal is to achieve this functionality with multiple links on the page. <div id="main-nav"> <div id="menu-container"&g ...

Exploring the potential of VSCode's RegEx search and replace

I am working on an Angular translation file and need to perform a search and replace operation in VScode for the translate key. The goal is to extract only the final key and use it in the replacement. The keys are structured with a maximum depth of 3 level ...

PHP enables downloading images on my server

Need help with implementing a functionality for saving images from an image search button: <div class="form-group"> <button onclick="myFunction()">Click me</button> <p id="demo"></p> <script> var lin ...

Exploring Image Quality in Headless Browsers - A Comparison of Headless Chrome, PhantomJS, and Slimmer

Exploring the inner workings of headless browsers has been a fascinating journey for me. I have experimented with various headless browsers in the past, including SlimerJS, Phantom.js, and Headless Chrome, primarily for capturing screenshots of different w ...

Toggle visibility between 2 distinct Angular components

In my application, I have a Parent component that contains two different child components: inquiryForm and inquiryResponse. In certain situations, I need to toggle the visibility of these components based on specific conditions: If a user clicks the subm ...

Using Three.js to create a variety of distinct lines

When creating maps using three.js, we typically incorporate dashed lines for borders and isolines. However, I am interested in exploring different line patterns for added visual interest. Does texturing offer a better approach to achieve this? UPD: The ma ...

Accessing the req property beyond the route endpoints

const express = require('express'); const router = module.exports = express.Router(); const server = require("http").Server(express); const io = require("socket.io")(server); server.listen(5000); // Need a way to access user.id here router.g ...

getting rid of the angular hash symbol and prefix from the anchor tag

I am having difficulty creating a direct anchor link to a website. Whenever I attempt to link to the ID using: where #20841 is my anchor tag. Angular interferes with the URL and changes it to: This functions properly in Chrome and Firefox, but i ...

Developing single-page application frontends without utilizing node or npm

As a backend java developer with experience in spring boot, I am now exploring the world of single page applications. One aspect that appeals to me about SPA frameworks, particularly Vue, is things like model-binding and the use of components and template ...