Home  >  Q&A  >  body text

javascript - Doubts about setTimeout and Promise

I don’t understand the difference between setTimeout(resolve('World'), ms); and setTimeout(resolve, ms, 'World');.


function timeout(ms = 100) {

  /*1. 为何这种写法,立即返回数据而不是等到过了 ms 后才返回*/
  // return new Promise((resolve, reject) => {
  //   setTimeout(resolve('World'), ms);
  // });

  /*2. 为何这种写法,等到过了 ms 后才返回*/
  return new Promise((resolve, reject) => {
    setTimeout(resolve, ms, 'World');
  });
}

timeout(1000)
  .then(value => {
    console.log(`Hello, ${value}`);
  })
  .catch(err => {
    console.error(err);
  });
代言代言2665 days ago787

reply all(5)I'll reply

  • 習慣沉默

    習慣沉默2017-06-12 09:23:50

    This is the difference between func() and func. The first parameter of setTimeout is func. If func() is used, it is equivalent to its return value being the first parameter.
    For example:

    function test(){
        console.log('this is test!');
        return function () {
            console.log('this is return!');
        }
    }
    
    setTimeout(test(), 1000);

    roughly equivalent to:

    console.log('this is test!');
    setTimeout(function () {
            console.log('this is return!');
        }, 1000);

    reply
    0
  • 三叔

    三叔2017-06-12 09:23:50

    The first parameter passed is executed immediately, not the function name

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-06-12 09:23:50

    has nothing to do with Promise. When you execute setTimeout(resolve('World'), ms);, the browser has automatically executed resolve('World'), for example:

    var test = function(value){
                console.log(value);
            }
            setTimeout(test('hello') , 2000);

    At this time the test is executed immediately.

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-06-12 09:23:50

    The first parameter of setTimeout must be a function

    A function

    A function

    (Why so many people don’t understand)

    setTimeout(resolve, ms, 'World'); where resolve is a function, so this section behaves normally
    setTimeout(resolve('World'), ms); where resolve('World' ) is not a function, what determines it is the return value type of resolve, but in any case, resolve has already been executed when registering the timer, so naturally there is no delay effect

    reply
    0
  • 巴扎黑

    巴扎黑2017-06-12 09:23:50

    ====================================
    The following answers are invalid: I did not review the question carefully. .
    There is generally no difference.

    Just! ! ! !

    IE browser has a problem with its support for setTimeout(resolve, ms, 'World'). (It seems that IE <= 9 will cause problems)

    Reference materials: (see the note with yellow background inside)

    WindowOrWorkerGlobalScope.setTimeout()

    reply
    0
  • Cancelreply