简体   繁体   English

SetInterval中的SetTimeout

[英]SetTimeout inside SetInterval

I'm using Node js as server. 我正在使用Node js作为服务器。 To avoid instant disconnecting of users on page refresh and give buffer time for reloading I'm using SetTimeout inside SetInterval as followed. 为了避免在页面刷新时立即断开用户的连接并给重新加载提供缓冲时间,我在SetInterval中使用SetTimeout,如下所示。 Users are added to the array "remove" on Disconnect event. 在Disconnect事件中,用户被添加到阵列“ remove”。 If the Users dont return then they are eventually removed. 如果用户不返回,则最终将其删除。 I'm doing this with the help of Cookies 我正在Cookies的帮助下进行此操作

var remove=[];
socket.on('disconnect', function(){ 
remove.push(socket.id);
});


setInterval(myTimer, 120000);
function myTimer()
{
  var removed = remove;
  remove=[];
  setTimeout(function()
  {
    for(i=0; i < removed.length; i++)
    {
      connection.query("DELETE FROM users WHERE socketid='"+removed[i]+"'");
      console.log(removed[i]+" is disconnected");
    }
  }, 60000);
}

The code is working totally fine. 该代码工作正常。
But is it ok to have this kind of loop on server side? 但是可以在服务器端进行这种循环吗? Will they ever overlap due to delaying of execution? 由于执行延迟,它们会重叠吗? Will it be executed on time? 会准时执行吗?

for (var i=0;i<=10;i++) {
   (function(ind) {
      setTimeout(function(){console.log(ind);}, 1000 + (3000 * ind));
   })(i);
}

It is fine to use loops at server side, but you need to take care of them by using closures, like in the above example. 在服务器端使用循环是可以的,但是您需要使用闭包来处理它们,就像上面的示例一样。 Closures will help them executing the code in the correct context, and will avoid overlap. 封闭将帮助他们在正确的上下文中执行代码,并避免重叠。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM