0

I am trying to make a program which sees if a click is made within 2 seconds of previous click. My Code for same is:

document.addEventListener("click",do,false);
var lastBack=0;
function do(e){
   if((new Date().getTime()-lastBack)<2000)
         { alert("you clicked within 2 seconds this time");}
   else         
         { document.write("Quickly click again");
          lastBack=new Date().getTime(); }
}

I just cannot figure out whats wrong with it but when i click, it just displays 'quickly click again' and nothing else happens.Even it doesnt repeat the same line when clicked after long wait.

1 Answers1

1
  1. NEVER document.write after load. The page will be wiped
    Why is document.write considered a "bad practice"?
    What damage is done by document.write()?

  2. do is a reserved word. Rename the function or make it anonymous

var lastBack = 0;

function doIt(e) {
  if ((new Date().getTime() - lastBack) < 2000) {
    alert("you clicked within 2 seconds this time");
  } else {
    document.getElementById("message").innerHTML = "Quickly click again";
    lastBack = new Date().getTime();
  }
}


window.addEventListener("load", function() { // when page has loaded
  document.addEventListener("click", doIt, false); // assign click handler
},false)  
<span id="message"></span>
mplungjan
  • 134,906
  • 25
  • 152
  • 209