2

I have been working with the asynchronous function setTimeout in javascript. The following code gives different results when the parameter is passed in one setTimeout function and not in another. Can someone explain this?

Code 1:

console.log("Before");
getUserId(2);
console.log("After");

function getUserId(id){
  setTimeout(() =>{
    console.log(id);
  }, 2000);
}

Output 1:

Before
After
2

and,

Code 2:

console.log("Before");
getUserId(2);
console.log("After");

function getUserId(id){
  setTimeout((id) =>{
    console.log(id);
  }, 2000);
}

Output 2:

Before
After
undefined
Prateek Oraon
  • 101
  • 1
  • 8
  • 1
    Possible duplicate of [How can I pass a parameter to a setTimeout() callback?](https://stackoverflow.com/questions/1190642/how-can-i-pass-a-parameter-to-a-settimeout-callback) – Kurtis Jungersen Jun 17 '19 at 16:45
  • 1
    Your naming of id the same in the callback method for setTimeout and the getUserId function is probably what is confusing you in the second example, they are 2 differently scoped variables, and you are not sending in a value when the setTimout callback is called. In your first example the id is captured by a closure. – BlackICE Jun 17 '19 at 16:47

4 Answers4

1

If you want to pass parameters to your callback you can put them after delay param. If you don't pass any parameters then your callback is called without any

setTimeout(function[, delay, param1, param2, ...]);

console.log("Before");
getUserId(2);
console.log("After");

function getUserId(id){
  setTimeout((id) =>{
    console.log(id);
  }, 100, id);
}
ponury-kostek
  • 7,824
  • 4
  • 23
  • 31
1

The parameter id inside the setTimeout callback will be undefined unless you assign a default value to it like the example

function parentMethod(parentId) {
  setTimeout((id = parentId) => {
    console.log(id);
  }, 2000);
}

Check this line setTimeout((id = parentId) => {

Here I am assigning a default value to it, so it will log whatever I assign to the parent method.

0

Because in sample 1 id is set in the scope of getUserId(id) In sample 2 the id is set again in that scope, but then a second narrower scoped id was created via your anonymous function. there is no need to pass setTimeout() the id parameter since it already exists in the getUserId scope

tstrand66
  • 968
  • 7
  • 11
0

In the second example, you are redefining scope for the variable id in the callback passed to setTimeout(). In other words this is the same as:

function getUserId(id){
  setTimeout((some_other_id) => {
    console.log(some_other_id);
    // some_other_id is undefined
  }, 2000);
}

Understanding the scope of id will explain / fix your problem.

Kurtis Jungersen
  • 2,204
  • 1
  • 26
  • 31