What is causing myInterval to not be cleared properly?

const homeButton = document.getElementById('home');
window.myInterval = 0;


const showHome = () => {
  console.log('showHome');
  window.myInterval = setInterval(wait, 400)
}

const wait = () => {
  console.log('wait');
  if (homeButton.style.visibility === 'visible') {
    console.log('clearingInterval');
    window.myInterval = clearInterval(myInterval)
  }
  window.myInterval = clearInterval(myInterval)
  homeButton.style.visibility = 'visible';
}

const waitUntil = () => {
  console.log('waitUntil');
  homeButton.style.visibility = 'hidden';
  window.myInterval = clearInterval(myInterval)
}</pre>
<pre class="snippet-code-css lang-css"><code>div {
  position: relative;
  width: 2%;
  height: 80vh;
  z-index: 1;
  transition: 0.5s;
  text-align: center;
  background-color: rgb(255, 250, 250);
  color: rgb(245, 241, 241);
  border: solid 2px rgb(243, 243, 243);
}

#home {
  visibility: hidden;
}

div:hover {
  width: 25%;
  text-align: center;
}

body {
  background-color: rgb(255, 252, 252);
}

#right {
  position: absolute;
  left: 5%;
  width: 92%;
  bottom: 4%;
  height: 95%;
  border: none;
  background-color: rgb(255, 252, 252);
  color: rgb(255, 252, 252);
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>repl.it</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
</head>

<body>
  <div onmouseover="showHome()">
    <button id="home" onclick="">Home</button>
  </div>
  <button id="right" onmouseover="waitUntil()">test</button>
  <script src="script.js"></script>
</body>

</html>

If you continuously hover over the home button division, it will start glitching and keep the home button visible. The console shows repeated 'wait' messages which means the interval is running endlessly without clearing. I attempted to clear it in the code:

  if (homeButton.style.visibility === 'visible') {
    console.log('clearingInterval');
    window.myInterval = clearInterval(myInterval)
  }
  window.myInterval = clearInterval(myInterval)

I am trying to clear the interval here.

To view the full page, visit

By pressing F12 on that page and hovering over the sidebar, you will notice the repetition of 'wait' followed by 'clearingInterval' in the console.

The 'waitUntil' function makes the element invisible temporarily but due to the interval, it reverts back to being visible.

Answer №1

If you want to display the home button only when its parent div is hovered over, a better approach than using intervals is to hide the button on mouseleave. Simply calling clearInterval(myInterval) won't achieve this design goal.

const homeButton = document.getElementById('home');

const showHome = () => {
  console.log('showHome');
  homeButton.style.visibility = "visible";
}

function unshowHome() {
  console.log('clear!');
  homeButton.style.visibility = "hidden";
}
div {
  position: relative;
  width: 2%;
  height: 80vh;
  z-index: 1;
  transition: 0.5s;
  text-align: center;
  background-color: rgb(255, 250, 250);
  color: rgb(245, 241, 241);
  border: solid 2px rgb(243, 243, 243);
}
#home {
  visibility: hidden;
}
div:hover {
  width: 25%;
  text-align: center;
}
body {
  background-color: rgb(255, 252, 252);
}
#right {
  position: absolute;
  left: 5%;
  width: 92%;
  bottom: 4%;
  height: 95%;
  border: none;
  background-color: rgb(255, 252, 252);
  color: rgb(255, 252, 252);
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <div onmouseenter="showHome()" onmouseleave="unshowHome()">
    <button id="home" onclick="">Home</button>
    </div>
    <button id="right" onmouseover="">test</button>
    <script src="script.js"></script>
  </body>
</html>

The reason why the interval is not cleared properly is due to reassigning the same variable window.myInterval for multiple intervals. This causes only the second interval to be cleared when using clearInterval(), while the reference to the first one is lost. The code snippet below demonstrates how this issue occurs.

window.myInterval = setInterval(function() {
  console.log("interval 1");
}, 1000);

window.myInterval = setInterval(function() {
  console.log("interval 2");
}, 1000);

clearInterval(window.myInterval);
clearInterval(window.myInterval);  // undefined

Answer №2

Instead of redefining window.myInterval, simply use clearInterval(myInterval) to stop the loop.

If that doesn't work, you can also try using clearInterval(window.myInterval) in case the interval was not declared globally.

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

Verify the channel where the bot is currently active and dispatch a message

I've been attempting to set up my bot to send a message when it joins a guild, but for some reason, it's not functioning as expected. Here is what I have tried (along with some other variations): const { PermissionsBitField } = require('dis ...

What would be the best approach to convert this jQuery code into a more structured object-oriented programming format

Recently, I began working on my first major front-end heavy website. My goal was to create a unique content management system-driven single-page website with over 100 internal pages. The URL would remain constant, but whenever a user clicked on any link b ...

Tips for updating React context provider state when a button is clicked

WebContext.js import React, { createContext, Component } from 'react'; export const WebContext = createContext(); class WebContextProvider extends Component { state = { inputAmount: 1, }; render() { return <WebC ...

I have come to realize that my understanding of how Sass nesting works was misguided

Currently struggling with understanding Sass nesting. Any explanations on where I went wrong would be greatly appreciated, as this is a beginner-level issue for me. Thank you in advance. .header { display: flex; height: 10vh; background-color: #13192 ...

Discover the method for tracking idle time with jQuery and PHP

I have a script that utilizes PHP sessions through a custom class. One of the methods in this class calculates the remaining seconds before the session expires. Whenever the user refreshes the page or opens a new one, the idle time counter is reset using ...

JavaScript alert system

Seeking advice on a situation. Here's the scenario I'm facing: In a messaging platform, I have an array of users who are currently online. When a new user joins the chat, I want to notify the first user in the array. If there's no response w ...

I encounter difficulties when retrieving data in Next.js

Within a Next.js project, there is code provided that retrieves data from an external API endpoint and then passes it as props to a component called Services. This Services component utilizes the received data to dynamically render different sections of th ...

The jquery script for the dynamic remove button is malfunctioning

I have successfully implemented code to display dynamic controls using jQuery. Below is the working code: <script type="text/javascript"> $(document).ready(function() { $("input[value='Add']").click(function(e){ e. ...

Tips on how to update the page and create a counter for a table view

I am working with an HTMLB Tableview where I need to regularly update its firstRowVisible property every 3 minutes with a dynamic value. For example, if it starts at zero, after 3 minutes it should be set to 21 and continue increasing by a certain interval ...

Creating a real-time text field update feature for a form using Google Script

One of my clients is dealing with a large number of contacts and to streamline the process, I created a form with a scrolling list for contact selection. However, the list has become too long to navigate easily. Is there a solution that would allow the c ...

Utilizing Selenium for automating button clicks

When attempting to click a button represented by the following HTML code: <a href="javascript:submitPage('V','All Notes','');" class="viewFilter">All Notes</a> I have made multiple attempts to ...

External JavaScript functions remain hidden from the HTML page

Having issues with JavaScript functions. I created functions in a separate file named index.js, but when I use them in index.html like "onclick = function()", the file doesn't recognize the function. <!doctype html> <html lang="{{ app()-> ...

The <el-dropdown> function is currently facing a problem and is unavailable for use

While using Element-Plus, I've encountered an issue with the el-dropdown component. It doesn't display as a functional dropdown menu when imported into my project. Below is the code snippet I have used: <template> <div> <el- ...

Display the HTML content retrieved from the SailsJS Controller

Exploring the world of SailsJS, I am on a mission to save HTML content in a database, retrieve it, and display it as rendered HTML. To achieve this goal, I have set up a sails model and a controller. This is what my model looks like: attributes: { ht ...

Encountering TypeError with Next.js and Firebase: Unable to access properties of undefined (specifically 'apps')

My goal is to create an authentication system using NextJS and Firebase. The issue I am facing is in my firebaseClient.js file, where I am encountering the error "TypeError: Cannot read properties of undefined (reading 'apps')". Here is a snipp ...

Can you please explain the meaning of this statement in JavaScript/Node.js with regards to the importance of the => operator and the async and await keywords being used here?

(1) This snippet of code is used to hash a password, but the syntax may be unclear. Why does it utilize async and await in this manner? And why doesn't the => symbol seem to define a function? const hashPassword = async password => await bcrypt ...

"I encountered an error stating that res.json is not a function while trying to establish a connection between ReactJS

dataset.list.js import React, { Component } from "react"; import Datasets from "./data"; import axios from "axios"; class App extends Component { render() { return <Datasets datasets={this.state.datasets} />; } ...

A guide to updating a button in Angular:

Currently, I have implemented a directive that displays 3 tabs at the bottom. However, I am curious to know if it is possible to swap out "exterior" for "interior" based on whether I am on the exterior or interior page. For example, when on the exterior ...

The Ion-icon fails to appear when it is passed as a prop to a different component

On my Dashboard Page, I have a component called <DashHome /> that I'm rendering. I passed in an array of objects containing icons as props, but for some reason, the icons are not getting rendered on the page. However, when I used console.log() t ...

Managing special characters in PHP: Understanding charsets

While working on my website using HTML and PHP, I am having an issue with special characters (Å, Á ...) appearing as on the screen when using the post function. Strangely enough, all other HTML content displays correctly. Any suggestions for a solution ...