Asynchronous JavaScript using Callbacks -


i new javascript , various resources have read javascript functions asynchronous if coupled callbacks. after searching rigorously 10+ days on web not find explanation on how callbacks in javascript run asynchronously. examples ajax given not provide clear answer, can explain how callbacks in javascript run asynchronously below code?

function myfunc(a,b,callback){     var callbackvalue = callback();     var add= a+b;     var subt= a-b;     var mult= a*b;     var div= a/b;     ...     ...     ...     ...     ...     var totalvalue= add+callbackvalue; }  function myfunc(a,b,function(){//complex scientific operation takes 10 secs }); 

as using callback in "myfunc" in above code, mean when callback() invoked in "myfunc", runs asynchronously , program flow continues var add= a+b; var subt= a-b; ......... ....... without waiting result of callback();?

yes , no. if don't use settimeout/setinterval, runs synchronously.

// alert after 5 seconds function func(f) {     f();     alert('hello'); }  func(wait5); 

but if use settimeout, can run in separate execution context. i'd google this, since it's rhetorical explain.

// alert immediately, wait 5 seconds function func(f) {     settimeout(f, 0);     alert('hello'); }  func(wait5); 

of course, wait5 in case function waits 5 seconds. can create function if you'd like, run while loop until 5 seconds has elapsed ( check using new date().gettime() )


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -