Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am new to JS and i am trying to move object from left to right while spinning clockwise, here i applied setinterval for movement animation from left to right and also for rotation. I am able to clearinterval Movement from left to right but unable to clearinterval my Rotation i don't know why please if you can take a look




<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

    window.topPos = '';

    var e = document.getElementById("aDiv");
    var s = 1;
    var rotate = false;

    var degrees = 0;


    function myInterval() {
      var eLeftPos = e.offsetLeft;
      e.style.left = (eLeftPos + s) + 'px';


      function rot() {
        degrees++;
        e.style.transform = 'rotate(' + degrees + 'deg)';
      }

      var rotID = setInterval(rot, 1000)

      var leftPos = (eLeftPos + s) >= 1000

      if ((eLeftPos + s) >= 1000) {
        clearInterval(rotID)
        console.log(rotID)
      }


      if ((eLeftPos + s) >= 1000) {

        clearInterval(internal)
      }


    }

    var internal = setInterval(myInterval, 100);

<!-- language: lang-css -->

    #aDiv {
      background: black;
      width: 80px;
      height: 80px;
      position: relative;
    }

    #aDiv1 {
      background: red;
      width: 80px;
      height: 80px;
      position: absolute;
    }

<!-- language: lang-html -->

    <div id="aDiv"></div>
    <button>Stop</button>

<!-- end snippet -->


What I have tried:

I have tried Clearinterval method, changing animation everything.
Posted
Updated 23-Jul-21 2:14am

1 solution

There are two JS functions for handling timed events: setTimeout[^] and setInterval[^]. The core difference between these two functions is that setInterval repeats, while setTimeout only happens once.

In your code you're starting this animation using setInterval, and then within the function that runs the animation you're starting another interval every time:
JavaScript
var rotID = setInterval(rot, 1000)

You clear this down only when:
JavaScript
if ((eLeftPos + s) >= 1000) {
  clearInterval(rotID)
  console.log(rotID)
}

Which means that every 100ms you're starting another interval at 1 second, and any that don't get cleared immediately just get left to run without any ability to cancel them. You could consider using setTimeout instead within the myInterval method, which will ensure that you don't end up stacking up interval timers. But even so, it means you're creating new timeouts set to 1 second ahead, every 100ms. I don't think this is what you're intending with your code?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900