Implementing timeouts for node.js callbacks

前端 未结 4 584
执念已碎
执念已碎 2020-12-25 11:07

This is a typical situation in node.js:

asyncFunction(arguments, callback);

When asynFunction completes, callback

4条回答
  •  旧时难觅i
    2020-12-25 11:43

    You could do something like this:

    function ensureExecution(func, timeout) {
        var timer, run, called = false;
    
        run = function() {   
            if(!called) {
                clearTimeout(timer);
                called = true;
                func.apply(this, arguments);
            }   
        };
    
        timer = setTimeout(run, timeout);
        return run;
    }
    

    Usage:

    asyncFunction(arguments, ensureExecution(callback, 1000));
    

    DEMO

    But note the following:

    • The timeout is started immediately when you call ensureExecution, so you cannot cache that function reference.

    • The arguments passed to the callback will differ. For example asyncFunction might pass some arguments to callback upon success, but if the function is called by the timeout, no arguments will be passed. You have to keep that it mind. You could also provide default arguments with which the function should be called in this case:

      function ensureExecution(func, timeout, args, this_obj) {
          // ...
          timer = setTimeout(function() {
              run.apply(this_obj, args);
          }, timeout);
          //...
      }
      

提交回复
热议问题