Cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

How to Start and Stop Image Rotation with JavaScript?

ANSWERED

I've got a refresh button that fires off a message to my companion app to go fetch some data via an API and then updates the text element values based off the returned data.

Here's the code for the image which rotates once on refreshing:

<g transform="translate(30,50%)">
  <image id="refresh" href="icons/refresh.png" />
  <animateTransform attributeType="rotate" begin="click" from="360" to="0" dur="0.8" easing="ease-in-out" />
</g>

I want the refresh icon to start rotating indefinitely on triggering the refresh and then stop rotating when the updated data comes back in.

How would I accomplish this? The update currently works fine, I just need to start and stop the image rotation using JavaScript.

 

Here's what I've got:

refresh.onclick = e => {
  if (peerSocket.readyState === peerSocket.OPEN) {
    peerSocket.send("refresh");
// TODO: Start rotating refresh icon (indefinitely)
} }

peerSocket.onmessage = evt => {
handleData(evt.data);
// TODO: Stop rotating refresh icon
}
Barry Michael Doyle
Best Answer
0 Votes
1 BEST ANSWER

Accepted Solutions

I wonder if you can just keep calling the event, while checking for a status change, once the status changes, stop animating. Something vaguely like this (untested).

 

 

  <animateTransform attributeType="rotate" begin="enable" from="360" to="0" dur="0.8" easing="ease-in-out" />
refresh.onclick = e => {
  if (peerSocket.readyState === peerSocket.OPEN) {
    peerSocket.send("refresh");
    start(); 
  }
}

peerSocket.onmessage = evt => {
  handleData(evt.data);
  stop();
}

let timerID = null;
let refresh = document.getElementById("refresh");

function start() {
timerID = setInterval(function() {
refresh.animate("enable");
}, 801);
}
function stop() {
clearInterval(timerID);
}

 

View best answer in original post

Best Answer
2 REPLIES 2

I wonder if you can just keep calling the event, while checking for a status change, once the status changes, stop animating. Something vaguely like this (untested).

 

 

  <animateTransform attributeType="rotate" begin="enable" from="360" to="0" dur="0.8" easing="ease-in-out" />
refresh.onclick = e => {
  if (peerSocket.readyState === peerSocket.OPEN) {
    peerSocket.send("refresh");
    start(); 
  }
}

peerSocket.onmessage = evt => {
  handleData(evt.data);
  stop();
}

let timerID = null;
let refresh = document.getElementById("refresh");

function start() {
timerID = setInterval(function() {
refresh.animate("enable");
}, 801);
}
function stop() {
clearInterval(timerID);
}

 

Best Answer

Hmmmm, that's a cleaner solution that removing the functionality all together 🙂 Thanks, I'll give it a shot tonight after work 😄

Barry Michael Doyle
Best Answer
0 Votes