Performance issues in onclick javascript handler

I wrote the game in a java script and while it is running it is slow to respond with a few clicks. Below is a very simplified version of the code I am using to handle clicks and still cannot respond to the second click with 2 unless you wait long enough. Is this something I just need to accept, or is there a faster way to be ready for the next click?

By the way, I am attaching this function using AddEvent from the quirksmode transcoding 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 can be seen at http://www.omega-link.com/index.php?content=testgame

+1


a source to share


4 answers


I think your problem is that the second click is being registered as a dblclick event and not as a click event. The change is quick, but the second click is ignored unless you wait. I would suggest going for a mousedown or mouseup event.



+2


a source


You can try to change the class name instead of removing / adding the div to the DOM (which is what the innerHTML property does).

Sort of:



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;
      }
    }
}

      

+3


a source


I believe your problem is a change innerHTML

that changes the DOM, which is a big performance issue.

+1


a source


Yes, you can compare the performance of innerHTML with document.createElement (), or even:

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

      

Profiling your code can be helpful as you are using various A / B refactorings:

+1


a source







All Articles