Reputation: 405
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
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