setTimeout(function() {
console.log("1");
}
console.log("2");
Basically, what I want to output “1” before “2”. How do I synchronize the callback function with the current “caller” thread?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can’t hold up the thread in JavaScript (other than the
alertandconfirmbuilt-ins), so the only ways to make yourconsole.log("2")happen after yourconsole.log("1")are:Put it in the timeout function:
…or in another function that that timeout function calls, although as you already have a function for the
setTimeout, it’s unclear (other than code organization) why you’d need a separate one.Put it in a separate function you pass to
setTimeoutwith a longer delay:…being careful that
longerDelayreally is sufficiently longer thandelaythat you don’t end up with a bit of chaos around scheduling.Note I said “the thread” above. Unless you’re using web workers, which have a specific syntax, JavaScript on browsers is single-threaded. Two JavaScript functions cannot run simultaneously, and aside from edge case browser bugs around
alertand ajax completions and the like (at least some versions of Firefox run your ajax completion callback while you have a function waiting onalert; strange but true, and nothing you can rely on cross-browser or even cross-version), you can’t pause one JavaScript function in its tracks while another JavaScript function runs.