以最小间隔触发 javascript 事件

发布于 2024-11-01 03:26:58 字数 606 浏览 3 评论 0原文

我想每当发生重复事件(点击“保存”按钮)时触发一个操作(例如“更新已保存!”消息),但在给定时间段内不要触发两次。

对于以下内容,我希望 excecuteFunction() 最多每 3 秒触发一次,但如果 setInterval 在 4.5 秒后被清除,我仍然希望它在 6 秒后再次触发。

var minimumTime = 3000; // minimum ms between events
function myTimedEvent() {
    if ( lessThanMinimumTime() )
        // loop through again
    else {
        executeFunction();
    }
}
window.setInterval(myTimedEvent, 500);

executeFunction() 可以在执行时创建一个时间戳,而 lessThanMinimumTime() 可以将该时间戳与当前时间进行比较,然后设置一个子间隔,然后由 清除该子间隔如果在最小时间范围内,则执行executeFunction()

一定有更好的方法。

I want to trigger an action (like an "Update saved!" message) whenever a repeated event occurs (hitting the "save" button) but not trigger it twice within a given time period.

For the following, I want excecuteFunction() to trigger at most once every 3 seconds, but if the setInterval is cleared after 4.5 seconds I would still want it to trigger again after 6 seconds.

var minimumTime = 3000; // minimum ms between events
function myTimedEvent() {
    if ( lessThanMinimumTime() )
        // loop through again
    else {
        executeFunction();
    }
}
window.setInterval(myTimedEvent, 500);

executeFunction() could create a timestamp on execution, and lessThanMinimumTime() could compare that timestamp to the current time, then set a sub-interval that's then cleared by executeFunction() if it's inside the minimum time range.

There must be a better way.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

咽泪装欢 2024-11-08 03:26:58

这将触发事件不超过每三秒一次(加上执行executeFunction()所需的时间),但如果事件在最后三秒内触发,仍然会调用executeFunction()。这是您要找的吗?

var minimumTime = 3000; // minimum ms between events
var lastFired = null;
var timer;
function myEventHandler(){
    var now = new Date().getTime();
    clearTimeout(timer);
    if(lessThanMinimumTime()){
        timer = setTimeout(myEventHandler, lastFired - now + minimumTime);
    } else {
        executeFunction();
        lastFired = now;
    }
}

function lessThanMinimumTime(){
    if(lastFired == null) return false;
    return lastFired > new Date().getTime() - minimumTime;
}

This will fire the event no more than once every three second (plus the time it takes executeFunction() to execute), but will still call executeFunction() if the event fires during the last three seconds. Is this what you're looking for?

var minimumTime = 3000; // minimum ms between events
var lastFired = null;
var timer;
function myEventHandler(){
    var now = new Date().getTime();
    clearTimeout(timer);
    if(lessThanMinimumTime()){
        timer = setTimeout(myEventHandler, lastFired - now + minimumTime);
    } else {
        executeFunction();
        lastFired = now;
    }
}

function lessThanMinimumTime(){
    if(lastFired == null) return false;
    return lastFired > new Date().getTime() - minimumTime;
}
二货你真萌 2024-11-08 03:26:58

试试这个:

Function.prototype.restrictCallsToInterval = function(sec){
    var self = this,
        last, queued, diff;

    return function(){
        var args = arguments;
        if(last && !queued && (diff = (new Date().getTime() - last + 1000*sec)) > 0){
            // queue this up
            queued = setTimeout(function(){
                self.apply(self, args);
            }, diff);

            return;
        }

        last = new Date().getTime();
        self.apply(self, args);
    }
};

function doSomething(x){
    console.log(x);
}

doSomething = doSomething.restrictCallsToInterval(3);
doSomething(22);
doSomething(23);

try this:

Function.prototype.restrictCallsToInterval = function(sec){
    var self = this,
        last, queued, diff;

    return function(){
        var args = arguments;
        if(last && !queued && (diff = (new Date().getTime() - last + 1000*sec)) > 0){
            // queue this up
            queued = setTimeout(function(){
                self.apply(self, args);
            }, diff);

            return;
        }

        last = new Date().getTime();
        self.apply(self, args);
    }
};

function doSomething(x){
    console.log(x);
}

doSomething = doSomething.restrictCallsToInterval(3);
doSomething(22);
doSomething(23);
小女人ら 2024-11-08 03:26:58

好吧,你要求“更好的方法” - 我认为确实没有更好的方法,但这是我能想到的最简单的方法:

var minimumTime = 3000; // minimum ms between events
var canFireEvent = true;
function myTimedEvent() {
    if (canFireEvent) {
        canFireEvent = false;
        window.setTimeout(function() {
            canFireEvent = true;
        }, minimumTime);
        executeFunction();
    }
}

使用一个布尔标志。不要搞乱日期。

概念证明
(尽管定时器间隔为 1 秒,但该函数每 3 秒执行一次)

Well, you asked for "better way" - I don't think there is really any better way, but this is the most simple way I can think of:

var minimumTime = 3000; // minimum ms between events
var canFireEvent = true;
function myTimedEvent() {
    if (canFireEvent) {
        canFireEvent = false;
        window.setTimeout(function() {
            canFireEvent = true;
        }, minimumTime);
        executeFunction();
    }
}

Using one single boolean flag. No messing with dates.

Proof of concept.
(Function executed every 3 seconds although the timer interval is 1 second)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文