Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
184
rated 0 times [  185] [ 1]  / answers: 1 / hits: 18435  / 13 Years ago, sun, december 4, 2011, 12:00:00

This is a typical situation in node.js:



asyncFunction(arguments, callback);


When asynFunction completes, callback gets called. A problem I see with this pattern is that, if asyncFunction never completes (and asynFunction doesn't have a built-in time-out system) then callback will never be called. Worse, it seems that callback has no way of determining that asynFunction will never return.



I want to implement a timeout whereby if callback has not been called by asyncFunction within 1 second, then callback automatically gets called with the assumption that asynFunction has errored out. What is the standard way of doing this?


More From » node.js

 Answers
3

I'm not familiar with any libraries that do this, but it's not hard to wire up yourself.



// Setup the timeout handler
var timeoutProtect = setTimeout(function() {

// Clear the local timer variable, indicating the timeout has been triggered.
timeoutProtect = null;

// Execute the callback with an error argument.
callback({error:'async timed out'});

}, 5000);

// Call the async function
asyncFunction(arguments, function() {

// Proceed only if the timeout handler has not yet fired.
if (timeoutProtect) {

// Clear the scheduled timeout handler
clearTimeout(timeoutProtect);

// Run the real callback.
callback();
}
});

[#88757] Friday, December 2, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
andrewb

Total Points: 259
Total Questions: 124
Total Answers: 90

Location: Ivory Coast
Member since Sun, Mar 7, 2021
3 Years ago
;