0

I have an animation of a car driving back and forth across the screen and have figured out how to flip the image when it reaches the right side of the screen and then again when it reaches the left side. However, I need to loop this JS event so the animation constantly shows the car driving in the correct 'direction.' The code below should give you an idea of what I'm working with, so if anyone could be so kind as to help this beginner figure out how to make it loop infinitely, I would greatly appreciate it.

*tl/dr

Basically I need the code below to loop infinitely.

var carorange = $('.org-car');
    setTimeout(function () {
        carorange.addClass('flipimg');
    }, 5000);
    setTimeout(function () {
        carorange.removeClass('flipimg');
    }, 10000);
Cœur
  • 37,241
  • 25
  • 195
  • 267
Colin Keany
  • 309
  • 1
  • 3
  • 9
  • Possible duplicate of [JavaScript Infinite Loop?](https://stackoverflow.com/questions/5835126/javascript-infinite-loop) – Cœur Jan 09 '19 at 16:27

1 Answers1

3

Use setInterval instead of setTimeout:

var carorange = $('.org-car');
setInterval(function () {
    carorange.toggleClass('flipimg');
}, 5000);

setInterval has a nother big advantage: You can stop the interval. So if you assign the interval to a variable, like var myTimer = setInterval..., you can stop it at any time using clearInterval(myTimer); :)

Sascha Gehlich
  • 1,007
  • 8
  • 12
  • 1
    Nit: setTimeout can be cancelled too, so it's not a "big advantage" for setInterval (and canceling is not necessarily any easier than not restarting or immediately terminating in the callback). setInterval does has a slight "re-prime" advantage/difference in terms of when the next tick is scheduled, but it's it. See http://stackoverflow.com/a/729943/2246674 – user2246674 Jun 23 '13 at 17:49
  • Using two intervals isn't a good idea. They'll likely get out of sync after a while. Just use one `5000` millisecond interval, and toggle the class. –  Jun 23 '13 at 18:07
  • Crazy Train is totally right. I just wanted to help quickly! ;) I edited the answer. – Sascha Gehlich Jun 23 '13 at 18:12
  • you're all a bunch of wizards. works like a charm! thanks everyone! – Colin Keany Jun 23 '13 at 18:22