Is setTimeout a good solution to do async functions with javascript?

JavascriptJquery

Javascript Problem Overview


Searching in the web about async functions, I found many articles using setTimeout to do this work:

window.setTimeout(function() {
   console.log("second");
}, 0);
console.log("first");

Output:

first
second

This works, but is a best practice?

Javascript Solutions


Solution 1 - Javascript

setTimeout(function(){...}, 0) simply queues the code to run once the current call stack is finished executing. This can be useful for some things.

So yes, it's asynchronous in that it breaks the synchronous flow, but it's not actually going to execute concurrently/on a separate thread. If your goal is background processing, have a look at webworkers. There's also a way to use iframes for background processing.

Update:

To further clarify, there's a difference between concurrency/backgrounding and asynchronous-ness. When code is asynchronous that simply means it isn't executed sequentially. Consider:

var foo='poo';
setTimeout(function() {
  foo='bar'
}, 100);
console.log(foo);

The value 'poo' will be alerted because the code was not executed sequentially. The 'bar' value was assigned asynchronously. If you need to alert the value of foo when that asynchronous assignment happens, use callbacks:

/* contrived example alert */
var foo = 'poo';

function setFoo(callback) {
  setTimeout(function() {
    foo = 'bar';
    callback();
  }, 100);
};
setFoo(function() {
  console.log(foo);
});

So yes, there's some asynchronous-ness happening above, but it's all happening in one thread so there are no performance benefits.

When an operation takes a long time, it is best to do it in the background. In most languages this is done by executing the operation on a new thread or process. In (browser) javascript, we don't have the ability to create new threads, but can use webworkers or iframes. Since this code running in the background breaks the sequential flow of things it is asynchronous.

TLDR: All backgrounded/concurrent code happens asynchronously, but not all asynchronous code is happening concurrently.

See Also: https://stackoverflow.com/questions/11233633/understanding-asynchronous-code-in-laymans-terms

Solution 2 - Javascript

By default, JavaScript is asynchronous whenever it encounters an async function, it queued that function for later. But if you want a pause js for you can do it use promises Case 1: output hello(will not wait for setTimeout) https://jsfiddle.net/shashankgpt270/h0vr53qy/

//async 
function myFunction() {
let result1='hello'
//promise =new Promise((resolve,reject)=>{
setTimeout(function(){ 
resolve("done");
result1="done1";
}, 3000);
//});
 //result = await promise
 alert(result1);
}
myFunction();

case 2: output done1(will wait for setTimeout) https://jsfiddle.net/shashankgpt270/1o79fudt/

async function myFunction() {
let result1='hello'
promise =new Promise((resolve,reject)=>{
setTimeout(function(){ 
resolve("done");
result1="done1";
}, 3000);
});
 result = await promise
 alert(result1);
}
myFunction();

Solution 3 - Javascript

var foo = 'poo';
setTimeout(function() {foo = 'bar'}, 100);
alert(foo);

A small correction to @tybro0103 's answer, during the execution of 'alert(foo)' the value 'poo' will not change because the code was not executed sequentially. The 'bar' value was assigned asynchronously and it will execute only after 100 millisecond, by that time alert will be executed.

The value of foo remains unaltered, during the execution of line alert(foo). And will change later on time. Check @vishal-lia comment.

Solution 4 - Javascript

I don't really understand complicated coding like you people. But I still have a question and my question is that, if Java Script is Syncrounous then how could Java Script excude the Asyncrounous function. Please enlighten me.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionviniciuswebdevView Question on Stackoverflow
Solution 1 - Javascripttybro0103View Answer on Stackoverflow
Solution 2 - JavascriptShashank GuptaView Answer on Stackoverflow
Solution 3 - JavascriptVaisakh RajagopalView Answer on Stackoverflow
Solution 4 - Javascriptuser2473131View Answer on Stackoverflow