Anshul
Anshul

Reputation: 179

SetTimeout() call without callback function behaves in unexpected manner

I was just experimenting with settimeout() function and in one attempt I wrote down the following code:

console.log(setTimeout('a', 1000));

When I executed this statement, I received the following output on my console: enter image description here

I do understand that the error a is undefined appears because setTimeout() expects a function as its first argument but why do I see the numbers 379, 380 on the console. I believe this is the number of seconds elapsed since the setTimeout() command was first executed in the current session. Am I correct about this? Could someone please explain in more detail.

Upvotes: 2

Views: 638

Answers (2)

Amardeep Bhowmick
Amardeep Bhowmick

Reputation: 16908

The number that you see in the console is the ID returned by the setTimeout() call, which you can use later to clear the time out i.e. cancel it.

For example:

const id = setTimeout(console.log, 1000, "this is cancelled");
clearTimeout(id); //cancelling the earlier timeout
setTimeout(console.log, 1000, "this is not cancelled");

From MDN docs:

The returned timeoutID is a positive integer value which identifies the timer created by the call to setTimeout(); this value can be passed to clearTimeout() to cancel the timeout.

There is also one variant of setTimeout() which acts like the eval() function which is not recommended for use and flagged by most security scanning tools which takes a string expression and evaluates the expression into JavaScript code and executes as soon as the timer expires for example:

const id = setTimeout("console.log('cancelled')", 1000);
clearTimeout(id);
setTimeout("console.log('not cancelled')", 1000);

In your code you have used this variant when you passed 'a', you got the error because when the interpreter evaluated your string it could not find a variable a in the current scope.

const a = 'This is a';
setTimeout('console.log(a)', 1000);

Upvotes: 1

robbannn
robbannn

Reputation: 5013

The numbers you see are timeoutID's returned by the setTimeout-function. The ID's can be used to cancel a timeout by passing it to clearTimeout.

Read more about setTimeout here and clearTimeout here.

Upvotes: 1

Related Questions