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;
}}