setTimeout not working for my game

setTimeout not working for my game
0

#1

I have a game i am trying to make. Point is, when i click on a monkey, the background should turn red for a while then should turn back to black. The setTimeout should it make it turn black again. Having no luck so far:


#2

Your code should be like:

mon1.onclick = () => {
  document.getElementById("hole1").style.backgroundColor = "red";
  points += 2;
  document.getElementById("points").innerHTML = points;
  setTimeout(function() {
  document.getElementById("hole1").style.backgroundColor = "black";
}, 1);
}

but i don’t see any reason in repeating all that code when you can make only two functions and get what element was clicked on one function and another function that will change your bg back to black by just passing the element that needs to be affected.


#3

you mean like this:

(mon1) => {
  document.getElementById("hole1").style.backgroundColor = "red";
  points += 2;
  document.getElementById("points").innerHTML = points;
  setTimeout(function() {
  document.getElementById("hole1").style.backgroundColor = "black";
}, 1);
}```

But i dont know how that will affect the mon1 element

#4

I meant to include your timeout function inside the click event


#5

Here a quick example on how you can achieve what you want in just a couple of lines of code using jquery.

I left out the logic for points increment.