设置超时函数CallBack静态variables

使用以下代码时:

var x = 5; setTimeout(function() { console.log(x); }, 2500); x = 10; 

输出是10,我完全明白为什么。

不过,我想在上面的例子中输出为5(或者更具体地说,当设置超时函数被调用时x的值,而不是在调用callback时的值)。

向我提出的一个select是调用函数并查找数据。

像这样的东西:

 var x = 5; var value_of_x_at_some_time = function() { return old_value_of_x; } setTimeout(function() { console.log(value_of_x_at_some_time()); }, 2500); old_value_of_x = x; x = 10; 

我理解这个想法,但是这意味着我需要通过一个数组来计算什么是正确的值。 这可能是正确的方式,但不适合我。

我正在编写一些软件来pipe理调度事件(使用节点调度),例如,我可以有一个AngularJS前端设置事件的特定时间/长度以及其他一些信息。

我可能同时有两个事件,所以当我在这个函数中查找时,我需要知道使用哪一个(假设我有两个“警报”,如果你愿意的话,一个callback将需要知道使用blah [x],并且需要知道使用blah [x + 1])。

我可以查看当前时间,find最近的时间已经过去,然后标记,如果我把它设置为做任何需要, 可能工作,但我想知道是否有一种方法来包装我使用的variables的当前状态作为(匿名?)函数的一部分。

基本上我正在编写一个DVR应用程序在nodejs中,我连接到Firebase来pipe理持久化数据,并在前端的AngularJS,所以我可以保持大部分的应用程序断开,我试图使用节点时间表,所以当我添加一个logging事件的angular度,我可以看到在firebase的数据变化,安排事件,并在callback火灾时开始logging相应的节目,我关心的是我可以有两个节目同时logging,我有pipe理正确的录音,我有一个可能的想法是这样的数据结构:

 var recording_event = { time: "1500", date: "01012015", length: "3600", //time in ms channel: "51", program: "1", scheduled: "true", recording: "false" } var blah[] = recording_events.... 

然后在被调用的函数中search数组。

 var lookup_value() { // loop through blah[] till you find the event closest to current time, // check if recording is true, if not // set the value of recording to true // else search for the next matching event // assume x is the index that matches correctly // finally return the event return blah[x]; } setTimeout(function() { var temp = lookup_value(); // set tuner to temp.channel // set tuner to temp.program // start recording for length of time temp.length }, 2500); 

但是,这似乎是我正在做更多的工作,然后我需要在我的脑海中,我希望只是推动这个数据作为function的一部分,所以基本上取代上述function与下面:

 temp = x //"newly secheduled event" setTimeout(function() { // set tuner to temp.channel (value at the time of the scheduling) // set tuner to temp.program (value at the time of the scheduling) // start recording for length of time temp.length (value at the time of the scheduling) }, 2500); 

在运行时或多或lessdynamic。 有没有办法做到这一点?

(我也不知道这是不是一个好的标题,我愿意提供build议)。

我没有详细阅读所有内容,但是我想你想创build一个新的范围来捕获variables的当前值。 函数创build范围,创build和调用函数的简单方法是使用IIFE

 var x = 5; setTimeout((function(y) { // this function is executed immediately and passed the current value of `x` return function () { // this is function that is passed to setTimeout // since every function is a closure, it has access to the IIFE parameter y console.log(y); }; }(x)), 2500); x = 10; 

另请参阅: JavaScript内部循环封闭 – 一个简单的实例

但是,还有一个更简单的选项:您可以使用.bind 特定的值绑定到函数的参数:

 setTimeout(function(y) { console.log(y); }.bind(null, x), 2500); 

.bind创build一个新函数,并将其设置为您传递给它的特定值。

只要解决您的问题的最重要部分:

 var x = 5; (function(currentX) { setTimeout(function () { console.log(currentX); }, 2500); })(x); x = 10; 

将显示5

编辑 :所有的费利克斯·克林说。 请注意,尽pipe我们在不同层次上创build了一个函数,但最终效果是一样的 – 重要的一点是存在一个函数,引入一个新的范围,并使用一个与原始x无关的新variables。

EDIT2 :伙计们,请菲利克斯多加一点回答,即使我本来打了10秒,他现在肯定是两个答案中最好的,不公平,他只有我的赞同:D