简体   繁体   中英

JavaScript's setInterval and when the function complete

I need to run a function on my node.js server, that completes the same task every 15 minutes. I Used for that setInterval as in example number 3 here - http://tinyurl.com/c2jj7dl . So, I got to something like this:

exports.start = function (list, callback){
    setInterval(stuffTop.loadstuff, 900000, list, function (parsedList) {

                // CODE STUFF HERE


                // THEN THE CALLBACK.
        callback(parsedDynamicList);

    });

}

Actually this stuff work, but the function gets completed for the first time - only after 900000MS. Is there an option to make to function complete (in the first round) - straight when called ? Thanks.

Use a function which recursivly calls itself:

foo = function(){
  doStuff()
  setTimeout(foo,900000)
}

In your case It would look like this:

exports.start = function (list, callback){
  var foo = function () {
    stuffTop.loadstuff(list, function(parsedList) {
      //CODE STUFF HERE
      //THEN THE CALLBACK
      callback(parsedDynamicList);
      setTimeout(foo,900000);
    });
  }
  foo();
}

The solution to your question is simple. Call the function before going into the setInterval. Like this:

    var callback=function(){}
    var list=['some','list'];
    var repeaterFunction = function(){console.log("do now!")}

    var start = function (list, callback){
        repeaterFunction();
    var repeater = setInterval(repeaterFunction, 5000, list, function(parsedList){
                    // CODE STUFF HERE
                    // THEN THE CALLBACK.
            callback(parsedDynamicList);

        });

    }   
    start()​

The fact that I use var repeater = setInterval(... allows for the clearInterval(repeater) whenever you wish.

Here's the fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM