javascript 循环 nodejs 中的 setInterval

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9717884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:35:29  来源:igfitidea点击:

setInterval in loop nodejs

javascriptnode.jsloops

提问by Jed

I know that there are other questions just like this but my code just doesnt seems to work. Could you have a look at my code and tell me where i am wrong.

我知道还有其他类似的问题,但我的代码似乎不起作用。你能不能看看我的代码,告诉我哪里错了。

 var mysql = require('mysql');

var client = mysql.createClient({
  user: 'jed',
  password: 'jed8703',
  host: 'localhost',
  database: 'jedtest'
});

//var query = client.query(
//  'INSERT INTO testtable '+
//  'SET testid = ?, name = ?, value = ?',
//  [1, 'test', 'test']
//);


client.query(
  'SELECT * FROM testtable',
  function selectCb(err, results, fields) {
    if (err) {
      throw err;
    }

    console.log(results[0].Name);
    for(var i in results)
        {
            (function(y)
            {
                setInterval(function() {
                  console.log(results[y].Name + 'value:' + results[y].Value );
                }, 5000 );
            })
        }
  }
);

client.end();

回答by Rob W

Don't forget to invoke the function:

不要忘记调用函数:

        (function(y)
        {
            setInterval(function() {
              console.log(results[y].Name + 'value:' + results[y].Value );
            }, 5000 );
        })(i); // <------- Added (i);

Note that your delay may not behave as expected. Currently, you're executing all methods after 5 seconds. Create a queue if you want to have a delay of 5 seconds between each call.

请注意,您的延迟可能不会按预期进行。目前,您将在 5 秒后执行所有方法。如果您希望每次调用之间有 5 秒的延迟,请创建一个队列。

回答by Sarfraz

You are not fullfilling yvariable, try replacing:

您没有填充y变量,请尝试替换:

   (function(y)
   {
      setInterval(function() {
        console.log(results[y].Name + 'value:' + results[y].Value );
      }, 5000 );
   })

With:

和:

   (function(y)
   {
      setInterval(function() {
        console.log(results[y].Name + 'value:' + results[y].Value );
      }, 5000 );
   })(i); // <------------------