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

前端 未结 3 1933
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 02:52

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

window.setTimeout(function() {
   console.log(\"second\")         


        
3条回答
  •  面向向阳花
    2020-11-27 03:16

    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

提交回复
热议问题