0

I'd like to set a timeout to make it appear as if a card is being thrown to the right when the user presses the right arrow key. The function is a part of an object. Ideally, i'd like to write something like this:

for (const i of Array(5).keys()) {
  let posX = i;
  **sleep(10);**
  this.topCard.style.transform =
      'translateX(' + posX + 'px) translateY(' + posY + 'px) rotate(' + deg + 'deg) rotateY(0deg) scale(1)';
}

Changed my code to this after reading up on how to set a timeout in javascript

throwRight() {
  let posX = 10;
  let posY = -300;
  let deg = 5;

  for (const i of Array(5).keys()) {
    setTimeout(function() {
      let posX = i;
      console.log(i)
      this.topCard.style.transform =
          'translateX(' + posX + 'px) translateY(' + posY + 'px) rotate(' + deg + 'deg) rotateY(0deg) scale(1)';
    },10)
}

but now it's complaining that "this" is not defined inside my method. I have the feeling I'm going about this in the wrong way. What's a good way to "do something slowly" in Javascript?

Muriel
  • 449
  • 4
  • 20
  • See the [linked question's answers]() for the `this` problem. But your animation is also going to run out of sync with the browser's page refresh. For animations you're generally best off using [`requestAnimationFrame`](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame) rather than (or sometimes in conjunction with) `setTimeout`. It requests a callback from the browser *just prior* to the browser repaining the display, which it typically does 60 times/second (roughly ever 16.7ms) though on some highish-end systems it can be faster than that. ... – T.J. Crowder May 01 '21 at 10:10
  • ... What you do is request the animation callback, then get the current time to find out how far along in your animation you should be. Then you update your element display to reflect where you are in the animation, and the browser paints the result. – T.J. Crowder May 01 '21 at 10:12
  • I'm not a CSS animation expert, but in this particular case, I'd think you could animate via CSS rather than using JavaScript for it. – T.J. Crowder May 01 '21 at 10:15
  • 1
    Thanks so much @T.J.Crowder - will look into this. Really appreciate you taking the time to read through my question! – Muriel May 01 '21 at 10:17

0 Answers0