Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 999
viniciuswebdev Avatar asked Oct 28 '13 03:10

viniciuswebdev


People also ask

Can I use setTimeout in async function?

Working with asynchronous functionssetTimeout() is an asynchronous function, meaning that the timer function will not pause execution of other functions in the functions stack. In other words, you cannot use setTimeout() to create a "pause" before the next function in the function stack fires.

Is setTimeout good practice?

Most of the time, we use “setTimeout()” to let some code run a certain period of time. However, it can cause problems when it is not used not carefully.

Is setTimeout deprecated in JavaScript?

We all know that passing a string to setTimeout (or setInterval ) is evil, because it is run in the global scope, has performance issues, is potentially insecure if you're injecting any parameters, etc. So doing this is definitely deprecated: setTimeout('doSomething(someVar)', 10000);

What is the alternative for setTimeout in JavaScript?

The setInterval method has the same syntax as setTimeout : let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...) All arguments have the same meaning. But unlike setTimeout it runs the function not only once, but regularly after the given interval of time.


1 Answers

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: Understanding Asynchronous Code in Layman's terms

like image 137
tybro0103 Avatar answered Sep 26 '22 03:09

tybro0103