以最小间隔触发 javascript 事件
我想每当发生重复事件(点击“保存”按钮)时触发一个操作(例如“更新已保存!”消息),但在给定时间段内不要触发两次。
对于以下内容,我希望 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这将触发事件不超过每三秒一次(加上执行executeFunction()所需的时间),但如果事件在最后三秒内触发,仍然会调用executeFunction()。这是您要找的吗?
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?
试试这个:
try this:
好吧,你要求“更好的方法” - 我认为确实没有更好的方法,但这是我能想到的最简单的方法:
使用一个布尔标志。不要搞乱日期。
概念证明。
(尽管定时器间隔为 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:
Using one single boolean flag. No messing with dates.
Proof of concept.
(Function executed every 3 seconds although the timer interval is 1 second)