Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make setTimeout in javascript work for a defined function?

Tags:

javascript

This is my code:

$(".btn").click(function() {
  var userChosenColor = $(this).attr("id");
  animatePress(userChosenColor);
})

function animatePress(currentColor) {
  $("." + currentColor).addClass("pressed");
}

setTimeout(animatePress,2000);

So when I press the button on my website, the "pressed" class is applied (to make it darker) but the setTimeout doesn't work to make it revert back to its original colour. I followed the layout for the functions carefully so I don't know why it's not working. Thanks in advance

Edit: This is my jquery script in my HTML, could it be because of that?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" charset="utf-8"></script>

1 Answers

This should work:

$(".btn").click(function() {
    var userChosenColor = $(this).attr("id");
    animatePress(userChosenColor);
    setTimeout(() => animatePress(userChosenColor),2000);
})

function animatePress(currentColor) {
  $("." + currentColor).toggleClass("pressed");
}
like image 196
Jon Avatar answered Feb 13 '26 09:02

Jon