Z
Z
zlodiak2018-02-25 11:38:42
JavaScript
zlodiak, 2018-02-25 11:38:42

Why does setTimeout() fire without a second argument?

There is this code:

setTimeout(() => {
    console.log('hello');
});

As you can see, this function does not have a second argument (delay in ms), but it still works. In addition, if you run it in the chrome browser console, then in addition to the phrase 'hello', some number is displayed.
Please explain the mysterious nature of setTimeout

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
SagePtr, 2018-02-25
@zlodiak

"Some digit" is the timeout identifier that the function returns, can be later used to pass to the clearTimeout function (cancels the timeout).
And the second argument is the delay in milliseconds, if not set, then 0 is used, but in reality this does not mean that the function will be instantly executed, it may take 16 ms or even more (depending on the load of the browser).

A
Arman, 2018-02-25
@Arik

I have everything working right now.
setTimeout() as well as setInterval() return a numeric ID of the counter so that it can be canceled via clearTimeout(timeoutId)/clearInterval(intervalId)

A
Anton Shvets, 2018-02-25
@Xuxicheta

because

var timeoutID = scope.setTimeout(function[, delay, param1, param2, ...]);

delay - optional parameter
delay - Optional
The time, in milliseconds (thousandths of a second), the timer should wait before the specified function or code is executed. If this parameter is omitted, a value of 0 is used, meaning execute "immediately", or more accurately, as soon as possible. Note that in either case, the actual delay may be longer than intended; see Reasons for delays longer than specified below.

those. if the delay is not defined, then zero is set.
And they already wrote about the timer identifier.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question