nodejs(五)同步异步--USING SETTIMEOUT INSTEAD OF SETINTERVAL TO FORCE SERIALIZATION


Let’s say you want a function that does some I/O — such as parsing a log fi le — that will periodically
be executed. Let’s give that function the generic name my_async_function. You could start by
using setInterval like this:

var interval = 1000;
setInterval(function() {
    my_async_function(function() {
      console.log('my_async_function finished!');
  });
},interval);

  However, you must ensure that none of these functions execute at the same time. You really can’t
guarantee that if you are using setInterval. If my_async_function takes one millisecond longer
than the interval you are using, they would run at the same time.


  You need to enforce that the interval between the end of one my_async_function and the start of
the next is the desired interval. Here is how you can do this:

 1 var interval = 1000; // 1 second
 2 
 3 (function schedule() {
 4    setTimeout(function do_it() {
 5       my_async_function(function() {
 6         console.log('async is done!');
 7         schedule();   //再次调用
 8       });
 9   }, interval);
10 }());

Here you are declaring a function named schedule (line 3) and invoking it immediately after
it is declared (line 10). This schedule function schedules the do_it function to be executed in
one second (the chosen interval). After one second passes, this anonymous function fires, calling

my_async_function (line 5). When this function finishes, the anonymous callback you passed to it

is invoked (line 6), calling the schedule function, which will again schedule the do_it function to
be executed in one second, thus restarting the cycle.

原文地址:https://www.cnblogs.com/yuyutianxia/p/3279403.html