The JavaScript runtime is a single-threaded environment – – that is, it executes a single command at a time (synchronous). However, the browser that hosts the JavaScript runtime runs in a multi-threaded environment (the operating system). This means that while the JavaScript runtime can only process one line of code at a time, the browser can be doing something else while that is happening.
So, to do synchronous programming, you don’t need to do anything special. Just write code. But, if that code asks the browser to do some work (through any one of the many Web API’s, such as an AJAX request, a Geolocation request, a setTimeout()
, etc.), the browser will perform those operations asynchronously from the JavaScript runtime. In those cases, you will need to set up a callback function for when the asynchronous operation is complete – you can’t know when that will be, but you can be prepared for when it finishes.
Here’s an example of code that does not involve a Web API (synchronous) call:
var x = "First";
console.log(x);
var y = "Third";
var z = "Second";
function test(){
console.log(z);
}
console.log(y);
test();
// This code will be run synchronously. The output will be:
"First"
"Third"
"Second"
Now, we’ll introduce a Web API call (setTimeout()
), which is handled outside of the JavaScript runtime. This example clearly demonstrates that the JS runtime cannot do two things at once.
console.log("...starting...");
// Note that the timer is passed 0, which would seem to indicate that it should run the
// passed function immediately, but that won't happen because the JS runtime MUST complete
// the synchronous processing of the current execution context and go into an idle state
// before any new code can be executed
setTimeout(function(){
console.log("Message from setTimeout()...COMPLETE");
}, 0); // <-- NOTE THE ZERO (AS IN RUN RIGHT NOW)
// This message will be shown before the setTimeout message because the JS runtime
// cannot do two things at once. It MUST finish this code block first.
console.log("...working...");
// Result: "...starting...", "...working...", "Message from setTimeout()...COMPLETE"
0
solved javascript: what is the best way to do synchronous programming [closed]