White Maskers White Maskers - 1 month ago 8
Javascript Question

Difference between two clicks didn't get well on this code

I'm new to javascript and that is why I'm asking this question. I just want the alert "unlocked" if the 'hash' key is pressed in a time interval of 9 sec after "key" is pressed, but it's not working as expected, can anyone help me?



document.getElementById("key").addEventListener("click",function(){
alert("enter # to unlock");
var time = (new Date()).getTime();
//alert(time);
});

document.getElementById("hash").addEventListener("click",function(){
var keytime = (new Date()).getTime();
//alert(keytime);
var diff = time - keytime;
alert(diff);
if(diff <= 9000){
alert("unlocked");
}
else{
alert("try again");
}

});

<button id="key">key </button>
<button id="hash">#</button>




Answer

You initialized time in the scope of the #key click listener. It can't be reach outside.

Set it outside as a global variable.

Variable scope documentation

 
var time = 0;

document.getElementById("key").addEventListener("click",function(){
  alert("enter # to unlock");  
  time = (new Date()).getTime();
  //alert(time);
});

document.getElementById("hash").addEventListener("click",function(){
  var keytime = (new Date()).getTime();
    //alert(keytime);
   var diff = time - keytime;
  alert(diff);
  if(diff <= 9000){
    alert("unlocked");  
  }
  else{
   alert("try again");  
  }
  
  });
<button id="key">key </button>
<button id="hash">#</button>