javascript - Doubts about setTimeout and Promise
代言
代言 2017-06-12 09:21:50
0
5
816

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);
  });
代言
代言

reply all(5)
習慣沉默

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);
三叔

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

淡淡烟草味

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.

曾经蜡笔没有小新

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

巴扎黑

====================================
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

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

WindowOrWorkerGlobalScope.setTimeout()

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template