Issue with JavaScript: Flag set to false does not halt the simple animation

My goal is to initiate animations when the mouse is pressed down and then immediately halt them once the mouse is released.

Upon pressing the mouse, I set a flag to true which triggers the animation of the corresponding button that was clicked. However, the issue arises when releasing the mouse, as setting the flag to false does not stop the animation. Despite not receiving any errors in my console, there seems to be a logical error causing this problem.

What mistake have I made here, and what steps can I take to rectify it?

https://jsfiddle.net/b4kn4w3g/2/

The critical code snippet:


function eventBundle(e) {
  if (e.target !== e.currentTarget) {
    if (e.target == parent.children[0]) {
      isDown = true;
      amount = "reduce";
    } else if (e.target == parent.children[1]) {
      isDown = true;
      amount = "increase";
    }
  }
  e.stopPropagation();
}
window.addEventListener("mouseup", function(){
 isDown = false;
 amount = "neutral";
});
function holdStuff() {
  if (isDown === true && amount === "increase") {
    maxValue += 100;
  } else if (isDown === true && amount === "reduce") {
    maxValue -= 100;
  }
  requestAnimationFrame(holdStuff)
}

Answer №1

In order to address the issue, ensure you include maxValue = minValue in your mouseup event listener. The problem arises from the fact that your update function adjusts incrementally (by 5) with minValue += 5; and minValue -= 5;. As you increase or decrease the max value by 100, it must reach there in increments of 5. By setting the maxValue to the current minValue, the change stops at the current state.

window.addEventListener("mouseup", function(){
    maxValue = minValue;
    isDown = false;
    amount = "neutral";
});

https://jsfiddle.net/nexrytes/

Answer №2

The animation keeps going even after the user releases their mouse button because the update function is set to run continuously. One suggestion is to follow Joseph's advice, or you could choose to halt the updating process when it is not needed. By using requestAnimationFrame, you can obtain an ID that can be stored like so:

requestID = window.requestAnimationFrame(callback);

Later on, you have the option to cancel the request by using this code:

cancelAnimationFrame(requestID);

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 there a feature in Angular similar to Vue.js's "computed property" functionality?

After mastering Vue.js, I recently dove into Angular 4 for a new project. I've found that most things in Angular are quite similar to Vue, with the notable exception of "Computed Property". In Vue, I could easily create a computed property that would ...

Regular expressions: Capturing characters that come after and before a designated symbol

Is there a way to extract all letters, both before and after an underline "_", in JavaScript using Regex while excluding specific words like "pi", "\Delta" and "\Sigma"? How can this be achieved in Regex JS? /\b([^e|_|\d|\W])&bso ...

Distribute the capabilities of the class

Is there a way to transfer the functionalities of a class into another object? Let's consider this example: class FooBar { private service: MyService; constructor(svc: MyService) { this.service = svc; } public foo(): string { ...

Toggle a Vue.js method to display responses for a particular question

Currently, I am in the process of developing a simple toggle feature for a FAQ section. The idea is that when a user clicks on an icon associated with a specific question, only that question's answer should be displayed. Although the function is oper ...

Stopping a function when another function is invoked in JavaScript

I've been immersing myself in the search for a way to halt one function if another is called or triggered in JavaScript. Initially, I believed it to be unattainable, but I'm open to having my perspective changed. My current focus lies within a t ...

Leveraging react-router for automatic redirection after form submission

My goal is to implement a search functionality on the page where users can enter a search term (name, email, username) and have the page filter out one card from all the cards based on the search value. I believe that upon pressing enter, we should redirec ...

I am attempting to retrieve the aria-expanded value using JavaScript, however, I keep receiving an "undefined" response

I'm attempting to dynamically change the class of a <span> element based on the value of the attribute aria-expanded. However, I am encountering an issue where it returns "undefined" instead of the expected value of true or false. Below is the ...

Utilizing Angular 5 routerLink for linking to absolute paths with hash symbols

I am facing an issue with a URL that needs to be opened in a new tab. Unfortunately, Angular generates this URL without the # symbol. Currently, we have implemented the following: <!-- HTML --> <a title="Edit" [routerLink] = "['/object/objec ...

Version 2 of the Microsoft Logo Animation

I made some changes to my Microsoft logo animation project. You can view the updated version on CodePen. Overall, I'm pretty happy with how it turned out except for one issue. I'm struggling to determine the right timing to end the animation so ...

Dimensions of Collada Element

This is my first time delving into the world of javascript, WebGL, and Three.js. I successfully added a dae 3D model to my scene, but now I need to determine its size in order to generate objects within it. However, upon adding the dae object, it appeared ...

Creating a quiz with just one question in React: A step-by-step guide

How can I add the functionality to handle correct and incorrect answers? I've designed a single-question quiz with multiple options. The Quiz component has been created. See the code snippet below: Quiz Component export default function Quiz(props) { ...

Edit content on the fly using ajax (add information to database)

I have a question that pertains to both UX and technical aspects. I am currently creating a list using ajax and PHP. I am unsure whether it is advisable to manipulate the DOM before the backend processes are complete. What potential issues could arise if ...

Persisting a single module using vuex-persistedstate

Is there a way to configure vuex-persistedstate so that only one module persists state through page refresh? Currently, when I use plugins: [createPersistedState()] inside the user module, it does not work. plugins: [createPersistedState()] only works wh ...

When a form filled out using JavaScript is submitted, Wicket is receiving blank values

I am attempting to create a cross-selection feature using two multiselect elements. When I click a button, a simple JavaScript function transfers a value from one multiselect to another. This functionality works well, but when I try to submit the form, I o ...

How can I stop an element from losing focus?

One issue I'm facing is that when I have multiple elements with the tabindex attribute, they lose focus when I click on any area outside of them. The Problem - In traditional desktop applications, if an element is not able to receive focus, clicking ...

The counter variable does not function properly within a setInterval function

I have encountered an issue with my scroll-counter variable inside the setInterval function. It increments by 1 each time the setInterval function runs, which is supposed to happen 20 times before stopping. However, I noticed that the value of this variabl ...

Is it feasible to insert the result of a JavaScript code into a PHP script?

Alternatively, you can view both codes side by side on the panelbackup(dot)com/codes page Alright, I have a code placed on page 1.html that adds four random numbers at the end of any given URL: <head><script>window.onload = function() { ...

Ways to trigger an event or invoke a function after initializing Stripe JS

My checkout page is optimized with the new Stripe Payment Element for fast loading using SSR. However, I am facing an issue where the element sometimes causes the page to reload 2 or more times before functioning properly. Occasionally, it also displays ...

I'm feeling a bit lost with this API call. Trying to figure out how to calculate the time difference between the

Currently, I am working on a project for one of my courses that requires making multiple API calls consecutively. Although I have successfully made the first call and set up the second one, I find myself puzzled by the specifics of what the API is requesti ...

Is Eslint functioning in just one Sublime Text project?

I have encountered an issue where I duplicated the .eslintrc and package.json files for two projects, but only the first project is able to run linting properly. The second project does not show any errors. I am using sublime-linter with the eslint modul ...