-2

I want to animate something everytime I click on it. So I saved an animation in the class "animation".

function listClick() {
  toplist.classList.add("animation");
  toplist.classList.remove("animation");
}

the animation lasts 2000 ms so I want a delay of 2000 ms between those two lines of code in my function. How can I achieve this using Javascript?

Michelangelo
  • 5,888
  • 5
  • 31
  • 50
H0ndman2
  • 41
  • 2
  • 8
  • 2
    Possible duplicate of [Put a Delay in Javascript](https://stackoverflow.com/questions/1183872/put-a-delay-in-javascript) – Abbe Jul 08 '17 at 19:03

3 Answers3

0
function listClick() {
     toplist.classList.add("animation");
     setTimeout(function() {
          toplist.classList.remove("animation");
     }, 2000);
}
Kovi
  • 138
  • 1
  • 1
  • 9
0

You have the setTimeout(function(), timeoutInMilliSecs); you can throw in there and use.

Subtractive
  • 500
  • 2
  • 9
  • 19
0

Create a new function

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

function listClick() {
    toplist.classList.add("animation");
    await sleep(2000);
    toplist.classList.remove("animation");
}

What is the JavaScript version of sleep()?

Jarvis
  • 1