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

前端 未结 2 1933
抹茶落季
抹茶落季 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条回答
  • 2021-01-20 07:42

    I use this wrapper function throughout my projects. Unfortunately at the time of writing I didn't know about the proper terminology throttling.

    // ignore fast events, good for capturing double click
    // @param (callback): function to be run when done
    // @param (delay): integer in milliseconds
    // @param (id): string value of a unique event id
    // @doc (event.timeStamp): http://api.jquery.com/event.timeStamp/
    // @bug (event.currentTime): https://bugzilla.mozilla.org/show_bug.cgi?id=238041
    ignoredEvent: (function () {
        var last = {},
            diff, time;
    
        return function (callback, delay, id) {
            time = (new Date).getTime();
            id = id || 'ignored event';
            diff = last[id] ? time - last[id] : time;
    
            if (diff > delay) {
                last[id] = time;
                callback();
            }
        };
    })(),
    

    You can use it like this:

    $(document).on('mousemove',function(event){
        ignoredEvent(function(){
            logMouse(event);
        }, 200, 'mouse-move');
    });
    
    0 讨论(0)
  • 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);
        } 
    });
    
    0 讨论(0)
提交回复
热议问题