• 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.

  • 相关阅读:
    List<T>的使用
    onclientclick和onclick区别
    IOS学习资料
    DataTable排序的一般方法
    jquery特效
    交叉表、行列转换和交叉查询经典
    sql截取查询
    DelPhi学习网站
    EasyDarwin开源云平台接入海康威视EasyCamera摄像机之快照获取与上传
    EasyDarwin开源云平台接入海康威视EasyCamera摄像机之快照获取与上传
  • 原文地址:https://www.cnblogs.com/yuyutianxia/p/3279403.html
Copyright © 2020-2023  润新知