Throttling a mousemove event to fire no more than 5 times a second

前端 未结 2 1936
抹茶落季
抹茶落季 2021-01-20 07:25

I have an event handler bound to the mousemove handler which will log the current mouse position via console.log().I am aiming to have the event fire no more than 5 times a

2条回答
  •  旧时难觅i
    2021-01-20 07:54

    Add a variable that tracks when an event has just occurred, and sleep with setTimeout before allowing the next event.

    var timesPerSecond = 5; // how many times to fire the event per second
    var wait = false;
    $(document).on('mousemove', function (event) {
        // don't handle events when one has just occurred
        if (!wait) {
            // fire the event
            logMouse(event);
            // stop any further events
            wait = true;
            // after a fraction of a second, allow events again
            setTimeout(function () {
                wait = false;
            }, 1000 / timesPerSecond);
        } 
    });
    

提交回复
热议问题