I'm currently reading 'You Don't Know Javascript' and ran across a problem with in an example of how to address a callback never running.
In the example listed below, I'm not sure how it works.
So the bottom code works first to check if there is an error or if the data is valid then the ajax request gets called with timeoutify(foo, 500).
When timeoutify is running it uses foo and 500 as parameters, it runs the first setTimeout function and in 500 milliseconds a timeout error will occur if the setTimeout isn't cleared.
However, the part I'm having trouble with the 2nd half starting with the if(intv) part. Doesn't timeoutify always get if(intv) set to true because the setTimeout is running first so the statement always return the 2nd half? When will the error timeout happen?
function timeoutify(fn,delay) {
var intv = setTimeout( function(){
intv = null;
fn( new Error( "Timeout!" ) );
}, delay );
return function() {
// timeout hasn't happened yet?
if (intv) {
clearTimeout( intv );
fn.apply( this, arguments );
}
};
}
Here is the preceding code:
// using "error-first style" callback design
function foo(err,data) {
if (err) {
console.error( err );
} else {
console.log( data ); }
}
ajax( "http://some.url.1", timeoutify( foo, 500 ) );