You can pass in some identifier into your foo() to keep track. Try this:
setTimeout(function () { foo(1); }, 10);
setTimeout(function () { foo(2); }, 10);
And modify your foo() function to accept the id argument and pass it around.
function foo(id) {
/* some statements */
bar(id);
}
function bar(id) {
try {
throw {
name: "Exception",
message: "oooh damn!" + id
}
} catch (e) {
console.error(e.name, e.message);
}
}
See example in fiddle: http://jsfiddle.net/amyamy86/Am8mf/
So, if I do:
setTimeout(function () { foo(1); }, 10);
setTimeout(function () { foo(2); }, 10);
Then it comes back:
Exception oooh damn!1
Exception oooh damn!2
Or if I do:
setTimeout(function () { foo(1); }, 10);
setTimeout(function () { foo(2); }, 9);
Then it comes back:
Exception oooh damn!2
Exception oooh damn!1
Edit #2 To not have to pass an id as argument:
var currentId = null;
function foo() {
var id = currentId; // since it's copied over to 'id', we don't care about 'currentId' anymore
var bar = function() {
try {
throw {
name: "Exception",
message: "oooh damn!" + id
}
} catch (e) {
console.error(e.name, e.message);
}
}
/* some statements */
bar();
}
setTimeout(function () {
currentId = 1;
foo();
}, 10);
setTimeout(function () {
currentId = 2;
foo();
}, 10);
So the currentId is a shared variable, but it is set at the moment of when the setTimeout() is over, and executes the function.
So doing:
setTimeout(function () {
currentId = 1;
foo();
}, 10);
setTimeout(function () {
currentId = 2;
foo();
}, 9);
Then it comes back:
Exception oooh damn!2
Exception oooh damn!1
setTimeoutcode execute first?foofunction has something asynchronous inside of it? Otherwise, it shouldn't be delayed compared to the second. Since they reference the same function (foo), the code executed is the same, so there's no reason the firstfoo();should ever execute after the secondfoo();(again, unless there's something asynchronous in it). Now, this would be different if the firstsetTimeoutcalledasdf()and the second calledfoo(). I wasn't sure if you were being very specific or broad. Just trying to understand the question better :)