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

Utilizing JavaScript files within Angular2 components: A guide

I need to insert a widget that runs on load. Typically, in a regular HTML page, I would include the script: <script src="rectangleDrawing.js"></script> Then, I would add a div as a placeholder: <div name="rectangle></div> The is ...

Run a PHP function using <button onclick=""> tag

Is it possible to trigger the execution of a PHP script when clicking an HTML button? I am aware that simply calling a PHP function directly from the button's onclick event like this: <button onclick="myPhpFunction("testString")">Button</butt ...

"NODEJS: Exploring the Concept of Key-Value Pairs in Object

I am facing a challenge with accessing nested key/value pairs in an object received through a webhook. The object in req.body looks like this: {"appId":"7HPEPVBTZGDCP","merchants":{"6RDH804A896K1":[{"objectId&qu ...

Challenge with adjusting opacity of background when hovering over a box

I've encountered an issue with the background transparency in the following demo. For some reason, it's not working properly. .figure .caption-mask:hover { background: rgba(0, 0, 0, 0.0); } I'm attempting to remove the opacity f ...

A common inquiry regarding Vue: How to effectively incorporate fullpage.js wrapper with additional functionalities

Having recently delved into Vue, I am currently tackling a project that involves the Fullpage.js Vue wrapper. While I have successfully implemented the Fullpage functionality, integrating additional features like an animation-on-scroll function has proven ...

AngularJS: monitoring changes in an array property

For the problem at hand, take a look at this link: http://plnkr.co/edit/ZphAKvZeoVtuGFSEmOKg?p=preview Imagine you have an array structured like this: var arr = [ { 'a': "123", 'b': "654" }, { 'a': "456", &apo ...

JavaScript Variables Lose Their Values

Similar Inquiry: How can I get the response from an AJAX call in a function? I have written a function that fetches numerical data from an online file. Although the file retrieval is successful (verified by the alert message), I encounter an issue whe ...

Looking to activate a button only when the checkbox is selected and in an enabled state

I'm struggling to make the button enable when the checkbox is checked and enabled. Additionally, it should be dependent on the textarea scroll above it. Once the checkbox is checked, the page needs to scroll up and down to activate the button. Here& ...

Is there a way to asynchronously load image src URLs in Vue.js?

Why is the image URL printing in console but not rendering to src attribute? Is there a way to achieve this using async and await in Vue.js? <div v-for="(data, key) in imgURL" :key="key"> <img :src= "fetchImage(data)" /> </div> The i ...

Matching Tables with JavaScript and JSON

After hours of coding, I'm stuck on a simple task and could really use some assistance. The "users" object contains user account information, with the function "get" meant to retrieve matching objects from this array. var users = [ { name ...

When a dialog box is displayed, a scrollbar will automatically appear

I've encountered a strange issue while working with Angular dialogs: A vertical scrollbar unexpectedly appears, even though I've set the dialog to have a fixed width. component.ts const dialog = this.dialog.open(DialogComponent, { width: ...

Error in TypeScript: Typography type does not accept 'string' type as valid

As I attempt to implement the Typography component from material-ui using TypeScript, I encounter a perplexing error message TypeScript is throwing an error: Type 'string' is not assignable to type 'ComponentClass<HTMLAttributes<HTMLE ...

Manipulate the way in which AngularJS transforms dates into JSON strings

I am working with an object that contains a JavaScript date, structured like this: var obj = { startTime: new Date() .... } When AngularJS converts the object to JSON (for instance, for transmission via $http), it transforms the date into a string as ...

Creating a countdown timer that is determined by the word count of a specific <div> element

What I have: A unique countdown timer that starts at 3 seconds and counts down to 0s. <div class="phrase"> This is a statement.</div> <p> <div style='font-family: Arial; font-size: 12px; color:gray'> <br><s ...

How come I can't capture discord.js promise rejections within event callbacks?

As I delve into creating a discord bot, I encountered an interesting problem. To simplify things, here is a snippet that encapsulates the issue at hand: const Discord = require('discord.js'); const client = new Discord.Client(); client.on(&apo ...

In Vue.js, is it possible to nest a <tr> tag inside another <tr> tag?

I've been working on a dynamic table in vue.js, using the code snippet below: <template> <tr class="left-align" v-for="(item,index) in itemList" :key="index.id"> <td>{{item.items}}</td> ...

Creating a button that redirects to an external link in CodeIgniter:

Hello everyone, I'm new here and I could really use some assistance with a problem. I am trying to link the button labeled 'lihat rincian' and each row of tables to redirect to an external link like Here's a snapshot of my datatables ...

What method is most effective for combining two JSON files in Angular?

My data includes a json file with a product list that looks like this: [{"id":76, "name":"A", "description":"abc", "price":199, "imageUrl":"image.jpg", "productCategory":[{ "categoryId":5, "category":null },{ "categoryId":6, " ...

Struggling to make jQuery code function properly in Wordpress, despite attempting to use noConflict

I have created a custom image grid gallery in WordPress using HTML and CSS, complete with popups and sliders. I had to code it myself because I couldn't find a suitable plugin that matched my design preferences. I have tested the functionality on my ...

Watch mp4 clips in various languages with ExpressJs

I have a question regarding streaming videos within my local network. My mp4 files contain multiple audio tracks in different languages. Is there a way to select a specific audio track to stream? For instance, could you specify a language as a query parame ...