Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

setInterval in loop nodejs

setInterval in loop nodejs

Problem

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();
Problem courtesy of: Jed

Solution

Don't forget to invoke the function:

        (function(y)
        {
            setInterval(function() {
              console.log(results[y].Name + 'value:' + results[y].Value );
            }, 5000 );
        })(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.

Solution courtesy of: Rob W

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

setInterval in loop nodejs

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×