如何重用此JavaScript超时关闭? [英] How do I reuse this JavaScript timeout closure?

查看:101
本文介绍了如何重用此JavaScript超时关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现以下用于实现超时的JavaScript代码(也许在Stack Overflow上):

I found the following piece of JavaScript code (maybe here at Stack Overflow?) for implementing a timeout:

var delay = (function() {
  var timer = 0;
  return function(callback, ms) {
    clearTimeout(timer);
    timer = setTimeout(callback, ms);
  };
})();

我是JavaScript的新手,所以我仍在努力尝试关闭。如果我在一个地方调用 delay(firstCallback,200),然后在此之后立即调用 delay(secondCallback,200),清除第一个超时回调,而第二个回调成功执行。

I'm new to JavaScript, so I'm still trying to wrap my head around closures. If I call delay(firstCallback, 200) in one place and then delay(secondCallback, 200) right after, the first timeout callback is cleared, while the second callback executes successfully.

如何在不同的实例中重用 delay 而不用覆盖其他实例? (不知道这些术语是否正确,但是希望可以理解我的意思。)因此,在上面的示例中,我希望两个回调都执行。

How do I reuse delay in different instances without overwriting other instances? (Not sure if those terms are correct, but hopefully it gets my point across.) So, in the above example, I want both callbacks to execute.

感谢您的

编辑:作为一个实际例子,我试图在输入字段上缓冲按键事件,以便仅在未按下任何键之后才执行回调持续200ms。但是我有多个输入字段,当前,当两个输入字段连续快速发生按键事件时,缓冲区就会中断。

As a practical example, I'm trying to buffer keypress events on an input field, so that the callback is only executed after no key has been pressed for 200ms. But I have multiple input fields, and currently the buffer breaks when two input fields have keypress events in quick succession.

推荐答案

要重用这样,更容易摆脱匿名函数并将其用作生成器。

To reuse this, it is easier to get rid of the anonymous function and use it as a generator.

var createDelayManager = function() {
  var timer = 0;
  return function(callback, ms) {
     clearTimeout(timer);
     timer = setTimeout(callback, ms);
  };
}


var delayManagerOne = createDelayManager();
delayManagerOne(firstCallback, 200);

var delayManagerTwo = createDelayManager();
delayManagerTwo(secondCallback, 200);

这是一个有效的小提琴:
http://jsfiddle.net/HJrM7/

Here is a working fiddle: http://jsfiddle.net/HJrM7/

但是,值得注意的是此关闭操作的目的是防止针对某个对象堆积多个回调。尽管这是一个非常不错的闭包,但它使您能够确保触发的最后一个事件是将要执行的事件。我经常使用此技术来防止闪烁或在重绘期间发生不必要的鼠标移出事件。

But, It is worth noting, that the point of this closure is to prevent multiple callbacks from getting stacked against some object. It is a really nice closure though that enables you to make sure that the last event triggered will be the one that gets acted on. I use this technique a lot to prevent flickering, or unwanted mouse out events during ie redraws.

这篇关于如何重用此JavaScript超时关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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