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

I don’t understand the difference betweensetTimeout(resolve('World'), ms);andsetTimeout(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 withPromise. When you executesetTimeout(resolve('World'), ms);, the browser has automatically executedresolve('World'), for example:

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

      At this time thetestis 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');whereresolveis a function, so this section behaves normally
        setTimeout(resolve('World'), ms);whereresolve('World' )is not a function, what determines it is the return value type ofresolve, but in any case,resolvehas already been executed whenregistering 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 forsetTimeout(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
            About us Disclaimer Sitemap
            php.cn:Public welfare online PHP training,Help PHP learners grow quickly!