Halt animation instantly using jQuery

Is there a way to permanently stop an animation on a webpage that is triggered every second? I have a button labeled "Stop" but when clicked, the animation stops momentarily before continuing. Is there another method to completely remove the animation? You can view my code here.

 $(document).ready(function() {
    setInterval(function() {
        $("#myImg").animate({top: '50%',left: '50%',width: '174px',height: '174px',padding: '10px'}, 500);
         $("#myImg").animate({ marginTop: '0',marginLeft: '0',top: '0',left: '0',width: '70px',height: '70px',padding: '5px'}, 600); 
   },1000);    
});


$("#stop").click(function(){
$("#myImg").stop();
});

​ Thank you

Answer №1

Check out the jsFiddle demo here!

  1. -Avoid using setInterval, utilize the .animate() callback to loop your animation function.
  2. -Make sure to nest your animate functions for better control.
  3. -Don't forget to use the .stop() method on your initial .animate() iteration to avoid animation buildups and clear unnecessary memory.
$(document).ready(function() {
    
   function animateImage(){
       $("#myImg").stop().animate({top: '50%',left: '50%',width: '174px',height: '174px',padding: '10px'}, 500, function(){
            $(this).animate({ marginTop: '0',marginLeft: '0',top: '0',left: '0',width: '70px',height: '70px',padding: '5px'}, 600, animateImage); // <-- the 'animateImage' callback
       });    // Look for the callback above :D --> 
    }
    animateImage(); // Let's get this going!


    $("#stop").click(function(){
        $("#myImg").stop();
    });

});

Answer №2

The constant recurrence of the setInterval() function results in a continuous addition of new calls to .animate() on your elements. This leads to the animation restarting even after you successfully stop it.

What is the reason for utilizing setInterval() in this scenario?

In any event, you will need to also terminate the scheduled tasks. One approach to achieving this is demonstrated below:

var schedule = setInterval(fn, 1000);
clearInterval(schedule);

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 attributes as scope properties within AngularJS

I am currently working on a directive and I need to pass the Attributes (Attrs) to the $scope, however, I am facing some difficulties in achieving this. Specifically, my goal is to assign attributes in my template based on the name set in my date-picker ta ...

"Implementing actions on a Node.js server upon button click with jQuery AJAX: A step-by-step guide

I'm encountering an issue where I want the server to execute a task after a button is clicked. Below is my HTML code snippet: <input name="like" id="like" value="Like" type="submit" /> <script> $('like').click(fu ...

Issue with Bootstrap 5: Mobile Menu Failure to Expand

I’ve been struggling with this issue for days now. I’ve searched everywhere for a solution, but to no avail. That’s why I’m turning to the experts here for help :-) The problem I’m facing is that my mobile menu won’t open. Nothing happens when ...

An error has occurred as ByChained is not recognized

Recently, I have been experimenting with selenium webdriverjs in javascript to locate an element that includes the partial text "hoi" as well as the text "hoe gaat het". I attempted to use ByChained for this purpose, but encountered an error stating that ...

Sharing FormikProps between components in React: A step-by-step guide

I am struggling to pass the necessary values and props that Formik requires to the component one level up. My approach involves using several small components for various forms, and I need to pass them through a complex component to be able to pass them do ...

React: Error parsing - Missing closing JSX tag for <input> element

I am currently learning React and am in the process of working on a new component. Here is the code snippet that I have so far: order-item.component.jsx: import React, { Component } from 'react'; import { connect } from 'react-redux'; ...

Removing an object from the scene using three.js

Is there a way to remove an object from a three.js scene? I am trying to delete a cube when a specific key is pressed, but so far I can only clear the entire scene instead of removing just one cube. ...

Leveraging multi-processing with NextJS and NodeJS

My tech stack includes NextJS for frontend development and NodeJS for backend development. I'm looking to implement child processes in my project. Could someone guide me on setting up NodeJS for this purpose? Additionally, I'm interested in utili ...

Aligning content vertically on mobile screens

I am struggling to align items on mobile resolution in a specific order: Image Content Image2 Content2 I have created a pen showcasing this issue on Codepen. Initially, I attempted using transform: translate, but it only worked for the content. The ...

methods for transferring javascript array to JAVA array with AJAX

I'm currently facing an issue with posting an array of JavaScript elements into a Java array of Strings. Here's the situation... The JavaScript code I have is as follows: var quantity_arr = new Array(); for (var i=0; i< <%= cart.size() % ...

What could be causing this form to continuously submit outdated parameters?

I have a comment form that appears multiple times on my page, as each comment is linked to a node, and multiple instances of each node are displayed. The issue arises when I try to submit a comment successfully via AJAX. Upon trying to send another commen ...

"JavaScript: Issue Encountered While Converting Hexadecimal to Decimal

I've been working on a custom function to convert hexadecimal to decimal in my Scratch project: function Hex2Decimal(hex){ var deci = 0; var num = 1; var hexstr = String(hex); hexstr = hexstr.toLowerCase(); var expon = 0; for( ...

Switch between background positions with jQuery

As a beginner with jQuery, I am facing a challenge in trying to make something work. On my Wordpress site, each page has a different background image for the body tag. I want to create a button that, when toggled, will cause the body background image to d ...

The image being displayed is significantly wider than the corresponding HTML element

I'm attempting to display this webpage in PNG format using npm's wkhtmltox: <!doctype html> <html> <head> <meta charset="utf-8"> <style> html, body { padding: 0; width: 340px; } ...

Ways to dynamically toggle visibility and hide elements by clicking outside the specified div

I have a div that, when clicked, displays a contact us form. This form toggles between being visible and hidden. How can I make it hide when clicked on another part of the document? Here is the code: function showContactForm(){ var formWidth = &apos ...

The Bootstrap 5 Accordion Content is not Showing Up

In my current project in vscode, I am using Bootstrap 5 to develop a website. Specifically, I am working on creating an accordion feature with Bootstrap 5. However, I encountered an issue where the accordion body does not show up when clicking on the acc ...

How to Make a Div Tag Fade Effect with JavaScript in an External File

*** New Team Member Notice *** I'm currently working on an assignment and trying to implement a simple fade effect on a box. While it seems like this should be straightforward, I'm encountering some obstacles. Currently, the button causes the bo ...

AngularJS - Filter out items from ng-repeat that match specific string criteria

After successfully cleaning up an external JSON URL feed by removing unnecessary special characters through a filter in my AngularJS code, I am now faced with the challenge of filtering out specific items from an ng-repeat based on a certain string. angul ...

Lerna: The Ultimate Guide to Installing External Packages Across Multiple Projects

We utilize Lerna for managing our mono-repo projects, and I am seeking the most effective method to install an external package in my projects while ensuring they all use the same version. Here is my project structure (my-Main-A and my my-Main-B both depe ...

Fading Out with JQuery

My page contains about 30 same-sized divs with different classes, such as: .mosaic-block, .events, .exhibitions, .gallery, .sponsors, .hospitality, .workshops, .lectures { background:rgba(0, 0, 0, .30); float:left; position:relative; overf ...