So i am using this guide to learn about async-ish behavior in JS. The example i am unable to wrap my head around is this
function asyncify(fn) {
var orig_fn = fn,
intv = setTimeout( function(){
intv = null;
if (fn) fn();
}, 0 )
;
fn = null;
return function() {
// firing too quickly, before `intv` timer has fired to
// indicate async turn has passed?
if (intv) {
fn = orig_fn.bind.apply(
orig_fn,
// add the wrapper's `this` to the `bind(..)`
// call parameters, as well as currying any
// passed in parameters
[this].concat( [].slice.call( arguments ) )
);
}
// already async
else {
// invoke original function
orig_fn.apply( this, arguments );
}
};
}
Usage :
function result(data) {
console.log( a );
}
var a = 0;
ajax( "..pre-cached-url..", asyncify( result ) );
a++;
So conceptually I understand it is attempting to force a function which would execute immediately , to run on the next tick of the event loop, which allows the variable a to be set to the value 1 and hence will always print 1.
The setTimeout section , is the part where I presume , it pushes the call to the next tick of the event loop. However, I am completely lost on the return section of the code.
Q) I know intv will be the timer id, what on earth is the black magic of orgin_fn.bind.apply mean. I know bind , ahem binds a value to a function to be called later , apply passes a this object and and argument array, but I am having a hard time understanding the entire invocation flow and I have never seen fb.bind.apply.
Q)The this object resolves to the Window when i run the code in the browser, why are all the arguments being concatenated on the window (global in this case) object.
Q)I understand this is POC, but is there a legitimate reason to have an else block here which executes the function any way. In which scenario do i see this being executed.
Cheers!