1

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();
2
  • It does not seem to be good design to create x intervals which in addition will be executed all at the same time. Commented Mar 15, 2012 at 10:35
  • 2
    I think the answers so far are correct as to why it doesn't work, but why are you using setInterval() in the first place? (Alarm bells go off in my head whenever I see setInterval() called from inside a loop...) Commented Mar 15, 2012 at 10:35

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

2

You are not fullfilling y variable, try replacing:

   (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); // <------------------

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.