Solution 1 :

You should

  • attach a click event once
  • keep a global count of how many clicks
  • check whether you’ve reached the end in call
var i = 0;

function call() {
  if(i == 5) {
    alert("Finished");
    return
  }
  setTimeout(() => {
    document.getElementById("shape").style.display = "block";
  }, Math.random() * 3000);
}

document.getElementById("shape").onclick = function() {
  this.style.display = "none";
  alert(++i);
  call();
}

call()
#shape{
  display:none
}
<div id="shape">Click me</div>

Solution 2 :

Try the following:

    let x = 0;
    
  document.getElementById("shape").onclick=function(){
    if(x>4) return;

    document.getElementById("shape").style.display="none";        
    x++;
    console.log(x);
    call();
  }
     
 function call(){
    // Add your own method here
    document.getElementById("shape").style.display="block";
}

Problem :

Hi:) I’m trying to create a game using Javascript which shows an image on the screen, then, if someone click on the image it should disappear, after a while, reappear and repeat the process 5 times. But when I run the code it’s increasing the number of ‘i’ automatically. I put those ‘alert 1’ and ‘alert 2’ to guide me and what happens is that the program shows me ‘alert 1’ 5 times, than it shows me ‘alert 2’ once, and only after, it let me click on the shape (way more than five times) after alerting the value of five every time. I’ve tried different approaches like using while… but nothing worked, and I can’t understand why.

The way I see it should run like: show me the image => click on it => alert the number of i => show the image again => repeat the process until i reaches the number 5 => alert 1 => alert 2

            function call(){
        
            setTimeout(Appear,Math.random() * 3000);
        }
        
        
        
        
        
        
        call();
        
        for( i=0;i<5;i++){
        
            document.getElementById("shape").onclick=function(){
                document.getElementById("shape").style.display="none";
                alert(i);
                call();
                
            }
            alert('alert 1')
        }
        

        
        alert   ('alert 2');

Comments

Comment posted by Andreas

Nothing in your script actually “clicks” on anything. You add an event handler that will be executed when someone clicks on the element with the id

Comment posted by Andreas

And

Comment posted by Alneto

It worked!! Thank you!! I just had to change the positon of “if x>4 return ” one line up to satisfy another condition and did not had to use the “function call()” because there’s one similar up in my code.

By