user1697646
user1697646

Reputation: 333

interval in nodejs app?

I'm newbie, and i try to create nodejs app (with mongo database). I have a problem with interval function. example:

In severside: I have peace of code:

var test = setInterval(function(){
               getData()
           },1000);
var getData = function(){
   // get data from database then return to client
}

Problem is how I control when getData is finish then excute next interval. As i know javascript is non blocking so interval and getData function is in different thread, right?

Anyone have solution for this?

Upvotes: 0

Views: 759

Answers (2)

nerdy beast
nerdy beast

Reputation: 789

I am doing something similar to this in a node.js app:

let _ = require('lodash');

function getData() {

    let previousResponse;

    let run = function() {

        let currentResponse = someMethodToGetDataFromDb();

        //Only send data to client if something has actually changed
        if(!_.isEqual(previousResponse, currentResponse)) {
            previousResponse = currentResponse;
            sendDataToClient(currentResponse);

            //This calls itself but ensures there is only ever one call to
            //the db at one time.
            setTimeout(run, 3000); 
        }

    };

    run();
}

Upvotes: 0

zag2art
zag2art

Reputation: 5182

You can use setTimeout instead of setInterval:

function getData(){
   // get data from database then return to client
   setTimeout(getData, 1000);
}

getData();

Upvotes: 1

Related Questions