Yan Kleber
Yan Kleber

Reputation: 405

How to identify an event and pass it as a parameter to the callback function in JS?

I made several tests and searched online but couldn't find a solution to this.

I have the following code below which spawns 4 timeout events.

for (let w=1; w<=4; w++) {
    var eventname = "event"+w;
    this[eventname] = setTimeout(DoStuff(this), 1000);
}

function DoStuff (myref) {
    console.log(myref)
}

I need a way of pass to the callback function a reference of whose of the 4 events is invoking it.

Any idea?

Upvotes: 0

Views: 29

Answers (1)

Emiel Zuurbier
Emiel Zuurbier

Reputation: 20944

The third and all subsequent parameters in the setInterval function can be used to pass parameters with.

So in your case, pass the eventname reference to setTimeout after the delay argument, and only reference the DoStuff function without calling it.

for (let w=1; w<=4; w++) {
  var eventname = "event"+w;
  this[eventname] = setTimeout(DoStuff, 1000, eventname);
}

Upvotes: 2

Related Questions