rav*_*ius 5 javascript ruby arrays node.js
JavaScript与Ruby的Array#compact等效吗?
长版....我按照blog.nemikor.com上的示例进行操作。他的最后一个示例关闭了旧请求,但随后pendings仍然充满了过时的请求。对我来说,这似乎是内存泄漏。
我的解决办法就是循环pendings使用filter如下,但是这看起来有可能是之间的竞争条件pendings.push和pendings = pendings.filter。我是偏执狂吗?如果存在比赛条件,我该如何解决?
var pendings = [];
// there is a route
app.get('/some/path', function (request, response) {
pendings.push({
response: response,
requestedAt: new Date().getTime()
});
});
setInterval(function () {
var expiration = new Date().getTime() - (1000 * 30);
pendings = pendings.filter(function (pending, index) {
if (pending.requestedAt > expiration) {
return true;
} else {
pending.response.writeHead(408, { 'Content-Type': 'text/plain' });
pending.response.end('');
}
});
}, 1000);
Run Code Online (Sandbox Code Playgroud)
JavaScript 中没有线程,因此不可能存在竞争条件。所有代码都是按顺序排列的,并且只有在运行完成后才会转移控制权。因此,您的间隔函数将在任何其他函数接触之前运行直到完成pendings。
这适用于像setTimeout和 之类的东西setInterval。
作为实验:如果您使用 1 秒后触发超时setTimeout。之后,您编写了一个阻塞 2 秒的 while 循环,您的超时将在此之后触发,比 1 秒长得多。
一些粗糙的东西:
var timer = setTimeout(function () {
alert("hi!");
}, 1000);
var now = new Date();
var till = new Date(now + 2);
while(new Date() < till) {} // block for 2 seconds
Run Code Online (Sandbox Code Playgroud)