Skip to content

Instantly share code, notes, and snippets.

@danscan
Last active January 4, 2016 06:39
Show Gist options
  • Save danscan/8583132 to your computer and use it in GitHub Desktop.
Save danscan/8583132 to your computer and use it in GitHub Desktop.
A simple way to execute a function with a time limit and an isolated context – useful for maintaining resource availability on platforms that allow multiple HTTP APIs to share infrastructure.
(function generateContext() {
var _startTime = Date.now(),
_timeout = 10000,
_timedOut = false,
_finish = function(error) {
clearTimeout(_timeoutTimeout);
_endTime = Date.now();
_totalExecutionTime = _endTime - _startTime;
if (error) {
console.log('request error: %s; total execution time: %sms', error.toString(), _totalExecutionTime);
} else {
console.log('request finished in %sms', _totalExecutionTime);
}
},
_context = {
id: 0,
params: { condition: true },
res: {
send: function(body) {
if (! _timedOut) {
console.log('Sending response body:', body);
_finish();
}
},
error: function(error) {
console.log('Sending request error response:', error.toString());
_finish(error);
}
}
},
_timeoutTimeout = setTimeout(function() {
_timedOut = true;
_context.res.error(new Error('Request timed out'));
}, _timeout),
_endTime,
_totalExecutionTime;
(function context(_Data, _id, _params, _res) {
new Function('Data', 'id', 'params', 'res', 'Data();console.log(id);console.log(params); setTimeout(function() { res.send("gotcha"); }, 12000);')(
_Data,
_id,
_params,
_res
);
})(
function Data() { console.log('Data data data...') },
_context.id,
_context.params,
_context.res
);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment