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); });
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:
roughly equivalent to:
The first parameter passed is executed immediately, not the function name
has nothing to do with
Promise
. When you executesetTimeout(resolve('World'), ms);
, the browser has automatically executedresolve('World')
, for example: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');
whereresolve
is a function, so this section behaves normallysetTimeout(resolve('World'), ms);
whereresolve('World' )
is not a function, what determines it is the return value type ofresolve
, but in any case,resolve
has 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 for
setTimeout(resolve, ms, 'World')
. (It seems that IEReference materials: (see the note with yellow background inside)
WindowOrWorkerGlobalScope.setTimeout()