0

Hi I have a Javascript function that does some animations on button click and has some sleeps inside, here is pseudocod:

const sleep = ms => new Promise(s => setTimeout(s, ms));

async function f(data) {
   ...
   while( arg ) {
      doAnimation
      await sleep(200)
   }
}

My problem is, when button is pressed second time before the end of the animation, weird staff happends - I have two animations going simultanoiusly.

My question is, what is the best way to stop this finction on button press and recall it. I thought about a flag, but I have trouble writing it in a way, so the running function would react to it and new called not.

Kq11
  • 87
  • 1
  • 7
  • 1
    `sleep(200)` doesn't do anything ... did you expect it to "pause" the while loop? – Bravo Nov 16 '20 at 09:37
  • 1
    The best way is to avoid execute a second time while the first one is running. You can [debounce/throttle it](https://css-tricks.com/debouncing-throttling-explained-examples/) – VLAZ Nov 16 '20 at 09:39
  • @Bravo it does when I add `await`, sorry, just wrote it as pseudocode – Kq11 Nov 16 '20 at 09:59
  • 1
    Well, that makes a huge difference – Bravo Nov 16 '20 at 09:59
  • 1
    I think easiest way to do that is disabling the button once animation started and enabling it once animation is done. You could also just use a flag as you said. Flag would be true if animation started and if flag is true you would cancel the function. – İbrahim Özcan Nov 16 '20 at 10:26
  • 1
    Yes, [a simple flag](https://stackoverflow.com/a/64758794/1048572) should do it – Bergi Nov 16 '20 at 10:29
  • @Bergi I have a question, becouse I mostly write in other languages - is that normal in java, that in script you vave global variables that you use in functions? For me it don't look like clean code, but, on the other havd, there is mamy things that I dont kniow how to write ... simpler – Kq11 Nov 16 '20 at 12:59
  • *javascript , not java of course :) – Kq11 Nov 16 '20 at 13:20
  • 1
    @Kq11 the flag should not be global, it should be scoped appropriately to the unit where you want to share state. You might want to have one flag per element you animate or something, or you might have a singleton flag that affects all animations in your entire application, or something in between - depending on what you need. – Bergi Nov 16 '20 at 13:24

0 Answers0