Realise that three is called immediately after two. If you want three to only be called once the setTimeout inside two expires, then you should call three in that setTimeout callback.
To achieve that, you can pass an argument to two:
function run() {
one();
two(three); // Tell "two" what to call when its timer expires
}
function one() {
console.log(1);
}
function two(callback) { // <-- callback argument
setTimeout(function() {
console.log(2);
callback(); // <---
})
}
function three() {
console.log(3);
}
run();
Promises
Once you start using setTimeout to chain several asynchronous pieces of code, you will soon get into what is a "callback hell".
So for completeness, here is an implementation using the modern async/await syntax for using promises:
// Generic helper function
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
async function run() {
one();
await two();
three();
}
function one() {
console.log(1);
}
async function two() {
await delay(0); // So to have the timeout involved...
console.log(2);
}
function three() {
console.log(3);
}
run();
setTimeoutintwo, since it's asynchronous? It's hard to know why you are asking that. Could you give more context?