node.js setTimeout Loop Issue

I'm new to node.js.

I have tried to create a setTimeout that executes a database SELECT Query and repeats 3 seconds after processing the SELECT results has completed.

  var newDBMessagesInterval = 3000;     // 3 Seconds
  (function newDBMessagesSchedule() {
    setTimeout(function() {
      dbNewMessagesQuery(function(dbResults,dbResultsLength) {

        console.log(dbResults);

        newDBMessagesSchedule();
      });
    }, newDBMessagesInterval)
  })();



function dbNewMessagesQuery(callback) {
  dbConnection.query("SELECT data1,data2,data3 FROM table WHERE condition=1;", function (dbError, dbResults, dbFields) {
    if(dbResults.length > 0) {
      callback(dbResults,dbResults.length);
    }
  });
  callback();
}

It appears the setTimeout number of loops increases each time it runs (eg: first one console.log(dbResults), but then 2times and then 4 etc). Also I'm not sure if its waiting on the database SELECT to completed before trying to process the next time.

Looking for some advise on how to create this loop correctly with node.js

thx

Answers


Your dbNewMessagesQuery calls callback twice. Once synchronously, and once after the db query succeeds. You should just be calling it once after the query is done. With your current code, for every call to newDBMessagesSchedule, you queue up two more calls to run later.

function dbNewMessagesQuery(callback) {
  dbConnection.query("SELECT data1,data2,data3 FROM table WHERE condition=1;", function (dbError, dbResults, dbFields) {
    callback(dbResults, dbResults.length);
  });
}

I'd also recommend not bothering to pass the length separately, and instead pass along the error if there is one. Currently you just assume there will never be an error.

function dbNewMessagesQuery(callback) {
  dbConnection.query("SELECT data1,data2,data3 FROM table WHERE condition=1;", function (dbError, dbResults, dbFields) {
    callback(dbError, dbResults);
  });
}

Need Your Help

Capture iOS Simulator video for App Preview

ios ios-simulator ios8 video-capture screen-capture

Okay, so we can now submit video previews of our apps on the App Store. According to Apple we should do so with an iOS8 device and OSX 10.10. The problem is you have to have all the different devic...

static variable in Javascript

javascript jquery angularjs

I want to create a static variable in java script. My requirement is "i created a global variable as var a = 'ABC'. But i am changing the variable value when i am doing some interaction with DOM. I...