Javascript - Track mouse position

后端 未结 11 1533
谎友^
谎友^ 2020-11-22 03:13

I am hoping to track the position of the mouse cursor, periodically every t mseconds. So essentially, when a page loads - this tracker should start and for (say) every 100 m

11条回答
  •  萌比男神i
    2020-11-22 03:46

    Here’s a combination of the two requirements: track the mouse position, every 100 milliseconds:

    var period = 100,
        tracking;
    
    window.addEventListener("mousemove", function(e) {
        if (!tracking) {
            return;
        }
    
        console.log("mouse location:", e.clientX, e.clientY)
        schedule();
    });
    
    schedule();
    
    function schedule() {
        tracking = false;
    
        setTimeout(function() {
            tracking = true;
        }, period);
    }
    

    This tracks & acts on the mouse position, but only every period milliseconds.

提交回复
热议问题