0

I was trying to add a timeout to a button animation with JQuery and JavaScript. At first I attemted this code:

setTimeout(playBtnSoundAndAnimate(currentSequence[last]), 2000);

This did not add any timeout. However when I wrote the code below the timeout worked:

setTimeout(function () {
    playBtnSoundAndAnimate(currentSequence[last]), 2000;}); 

Why do I need to pass "playBtnSoundAnAnimate" in an anonymous function for setTimeout to take effect?

If it matters, here is how the "playBtnSoundAndAnimate" function look like:

function playBtnSoundAndAnimate(activatedBtn) {
  $("#" + activatedBtn).addClass("pressed");
  setTimeout(function () {
    $(".btn").removeClass("pressed");
  }, 50);

  switch (activatedBtn) {
    case "green":
      const greenAudio = new Audio("sounds/green.mp3");
      greenAudio.play();
      break;
    case "red":
      const redAudio = new Audio("sounds/red.mp3");
      redAudio.play();
      break;
    case "yellow":
      const yellowAudio = new Audio("sounds/yellow.mp3");
      yellowAudio.play();
      break;
    case "blue":
      const blueAudio = new Audio("sounds/blue.mp3");
      blueAudio.play();
      break;

    default:
      break;
  }}
Ivar
  • 6,138
  • 12
  • 49
  • 61
Nora
  • 1,825
  • 8
  • 31
  • 47

1 Answers1

-1

Looking at the docs, the function setTimeout accepts either code or a callback function as a first parameter. How this works is that this code of that callback function is put on the callback queue when the timer expires.

Bart Barnard
  • 1,128
  • 8
  • 17