Damien
Damien

Reputation: 273

How to pass an index into setTimeout

I know there are a lot of questions similar to this on here, but none that I've seen answer this for me. If I missed one, and this is a duplicate, sorry.

I'm trying to modify my graph using d3 and want to use setTimeout to space the operations in a nice looking way.

I have

for (var key in alist){
    setTimeout(function () {
        graph.removeLink(alist[key].source.name, alist[key].target.name);
    }(key), key*500+200);
}

This calls the removeLink function immediately instead of waiting the set interval.

I'm new to javascript, so sorry if this is something exceptionally obvious, I can't find an answer anywhere.

Upvotes: 0

Views: 1239

Answers (2)

Jesse Kernaghan
Jesse Kernaghan

Reputation: 4634

You can bind the variable to the anonymous function on the fly, or create a function to wrap the timeout in.

Anonymous function bind:

for (var key in alist){
    setTimeout(function (alistitem) {
        graph.removeLink(alistitem.source.name, alistitem.target.name);
    }.bind(this, alist[key]), key*500+200);
}

Separate function:

function timedRemoveLink(item, time){
   setTimeout(function() {
     graph.removeLink(item.source.name, item.target.name);
   }, time);
};

for (var key in alist){
    timedRemoveLink(alist[key], key*500+200);
}

Upvotes: 2

just.another.programmer
just.another.programmer

Reputation: 8785

You called your anonymous function when you tried to pass the key in. Instead, use a closure. Make sure to make a local copy of the key!

for (var key in alist){
    var keyCopy = key;

    setTimeout(function () {
        graph.removeLink(alist[keyCopy].source.name, alist[keyCopy].target.name);
    }, key*500+200);
}

Upvotes: 0

Related Questions