Frizi
Frizi

Reputation: 2940

document.onmousemove delay

I'm trying to build an expensive script with mouse and keyboard control on canvas. I'm using document.onmousemove and document.onkeydown/onkeyup to do this control, but when i press any button, i've got a lot of "onkeydown" executions, and mouse lags terribly. It looks like "write-only mouse position buffer" or something. When i release the key, mouse "simulate" my earlier moves. I tested it on Firefox and chrome, this problem exist only on FF.

here is some code

    document.onmousemove  = function(e){
        obj = canvas;
        var curleft = curtop = 0;

        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);

        mX = e.pageX - curleft;
        mY = e.pageY - curtop;
    }

    var dt=0.02;
    setInterval(tick, dt*1000);
    update(dt);
    function tick() {

        if((!pause) || step)
        {
            update(dt);
            step = false;
        }
        interact();
        draw();
    }

Upvotes: 1

Views: 1120

Answers (1)

casablanca
casablanca

Reputation: 70721

Depending on how complex your update, interact and draw functions are, your timer interval of 20 ms may be too short and taking up a lot of CPU time. Since JavaScript runs in a single thread, this can prevent your script from processing the mouse events.

These events can queue up in the browser's input queue and be dispatched to your script later (which is probably happening in Firefox) or they may be discarded if your script doesn't process them quickly enough (which might be happening in Chrome).

Some possible workarounds:

  1. Increase the timer interval.
  2. Instead of using setInterval, try using setTimeout after each execution of tick -- this will prevent multiple timer events from queuing up and firing together.

Upvotes: 3

Related Questions