Tutorial :Performance issues in javascript onclick handler


I have written a game in java script and while it works, it is slow responding to multiple clicks. Below is a very simplified version of the code that I am using to handle clicks and it is still fails to respond to a second click of 2 if you don't wait long enough. Is this something that I need to just accept or is there a faster way to be ready for the next click?

BTW, I attach this function using AddEvent from the quirksmode recoding contest.

var selected = false;  var z = null;  function handleClicks(evt) {      evt = (evt)?evt:((window.event)?window.event:null);      if (selected) {          z.innerHTML = '<div class="rowbox a">a</div>';          selected = false;      } else {          z.innerHTML = '<div class="rowbox selecteda">a</div>';          selected = true;      }  }  

The live code may be seen at http://www.omega-link.com/index.php?content=testgame


I think your problem is that the 2nd click is registering as a dblclick event, not as a click event. The change is happening quickly, but the 2nd click is ignored unless you wait. I would suggest changing to either the mousedown or mouseup event.


You could try to only change the classname instead of removing/adding a div to the DOM (which is what the innerHTML property does).

Something like:

var selected = false;  var z = null;    function handleClicks(evt)   {      var tmp;        if(z == null)         return;        evt = (evt)?evt:((window.event)?window.event:null);      tmp = z.firstChild;      while((tmp != null) && (tmp.tagName != 'DIV'))          tmp = tmp.firstChild;      if(tmp != null)      {        if (selected)         {          tmp.className = "rowbox a";          selected = false;        } else         {          tmp.className = "rowbox selecteda";          selected = true;        }      }  }  


I believe your problem is the changing of the innerHTML which changes the DOM which is a huge performance problem.


Yeah you may want to compare the performance of innerHTML against document.createElement() or even:

el.style.display = 'block' // turn off display: none.  

Profiling your code may be helpful as you A/B various refactorings:

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »