如何使用jQuery / javascript将事件的处理限制为每X秒一次? [英] How to limit handling of event to once per X seconds with jQuery / javascript?

查看:89
本文介绍了如何使用jQuery / javascript将事件的处理限制为每X秒一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于快速解雇 keypress 事件,我想将事件的处理限制为每 X 秒最多一次。

For a rapidly-firing keypress event, I want to limit the handling of the event to a maximum of once per X seconds.

我已经在使用jQuery进行事件处理,所以基于jQuery的解决方案会更受欢迎,尽管vanilla javascript也很好。

I'm already using jQuery for the event handling, so a jQuery-based solution would be preferred, though vanilla javascript is fine too.

  • This jsfiddle shows keypress firing rapidly without any limiting on the handling

这jsfiddle 使用 setTimeout()

我的问题是


  1. jQuery是否有内置的方式这样做?我在 .on() docs中看不到任何内容

如果没有,在vanilla JS中执行此操作是否比我在第二个jsfiddle示例

If not, is there a better pattern for doing this in vanilla JS than I've used in my second jsfiddle example?


推荐答案


jQuery有内置方法吗?

Does jQuery have an inbuilt way of doing this?

否。


如果没有,在我的第二个jsfiddle示例中使用的香草JS中是否有更好的模式?

If not, is there a better pattern for doing this in vanilla JS than I've used in my second jsfiddle example?

您可以跟踪时间,而不是使用 setTimeout 和标志处理程序最后一次调用,只在定义的间隔过去后调用它。这称为限制,有多种方法可以实现此目的。

Instead of using setTimeout and flags, you can keep track of when the handler was called the last time and only call it after a defined interval has passed. This is referred to as throttling and there are various ways to implement this.

在最简单的形式中,您只需忽略在 lastCall + interval 时间内进行的每次通话,这样每个区间只能进行一次调用。

In its simplest form you just have to ignore every call that is made within the time of lastCall + interval, so that only one call in every interval occurs.

例如。这是一个返回一个新函数的函数,只能每隔X毫秒调用一次:

E.g. here is a function that returns a new function which can only be called once every X milliseconds:

function throttle(func, interval) {
    var lastCall = 0;
    return function() {
        var now = Date.now();
        if (lastCall + interval < now) {
            lastCall = now;
            return func.apply(this, arguments);
        }
    };
}

您可以将其用作

$("#inputField").on("keypress", throttle(function(event) {
   $("div#output").append("key pressed <br/>");  
}, 500));

DEMO

as Esailija 他的评论,也许这不是你需要的限制,而是 debouncing 。这是一个类似但略有不同的概念。虽然限制意味着每隔x毫秒才会发生一次,但 debouncing 意味着只有在最后x毫秒内没有发生某些事情时才会发生。

As Esailija mentions in his comment, maybe it is not throttling that you need but debouncing. This is a similar but slightly different concept. While throttling means that something should occur only once every x milliseconds, debouncing means that something should occur only if it didn't occur in the last x milliseconds.

一个典型的例子是滚动事件。将经常调用滚动事件处理程序,因为事件基本上是连续触发的。但也许你只想在用户停止滚动时执行处理程序,而不是滚动时执行。

A typical example is the scroll event. A scroll event handler will be called very often because the event is basically triggered continuously. But maybe you only want to execute the handler when the user stopped scrolling and not while he is scrolling.

实现这一目的的一个简单方法是使用超时并取消它,如果再次调用该函数(并且超时尚未运行):

A simple way to achieve this is to use a timeout and cancel it if the function is called again (and the timeout didn't run yet):

function debounce(func, interval) {
    var lastCall = -1;
    return function() {
        clearTimeout(lastCall);
        var args = arguments;
        var self = this;
        lastCall = setTimeout(function() {
            func.apply(self, args);
        }, interval);
    };
}

此实现的缺点是您无法从事件处理程序返回值(例如 return false; )。也许有一些实现可以保留这个功能(如果需要)。

A drawback with this implementation is that you cannot return a value from the event handler (such as return false;). Maybe there are implementations which can preserve this feature (if required).

DEMO

这篇关于如何使用jQuery / javascript将事件的处理限制为每X秒一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆