I am new to JavaScript and from various resources i have read that JavaScript functions are Asynchronous if they are coupled with Callbacks. After searching rigorously for 10+ days on web i could not find an explanation on how Callbacks in JavaScript run Asynchronously. Some examples with AJAX are given but they do not provide a clear answer, can anyone explain how callbacks in JavaScript run Asynchronously for the 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 which takes 10 secs });
As i am using a callback in "myFunc" in the above code, does that mean that when callback() is invoked in "myFunc", it runs asynchronously and the program flow continues with var add= a+b; var subt= a-b; ......... ....... without waiting for result of callback();?
setTimeout
,setInterval
, event handlers, web workers, etc. So depending on what the callback is doing when you say "which takes 10 secs", if it doesn't use an asynchronous feature, it's not asynchronous. – Ian 12 hours agosetTimeout
is scheduled to run 1000ms from the timesetTimeout
was executed. Therefore, thetest
function can't return the value needed, and instead you have to use a callback so that the callback has access to the value when it's available (1000ms from then) – Ian 12 hours ago