Max Yari
Max Yari

Reputation: 3697

setTimeout giving arguments to function from another function

Got a problem, don't know how can I give to ClickSimClick function arguments exposed by ClickSimMove func (it returns array with 2 values).

Code below says that crd is undefined on setTimeout.

var crd = plugin().ClickSimMove();
setTimeout("plugin().ClickSimClick(crd[0], crd[1])", 1000);

Upvotes: 0

Views: 73

Answers (2)

Brad Christie
Brad Christie

Reputation: 101604

var crd = plugin().ClickSimMove();
setTimeout(function(){
  plugin().ClickSimClick(crd[0], crd[1]);
}, 1e3);

When at all possible, avoid sending strings to setTimeout/setInterval--use an anonymous function instead. Especially if you find yourself concatenating variables to make that string, you can run in to trouble very quickly with some sort of injection or malformed component.

Upvotes: 1

icktoofay
icktoofay

Reputation: 129001

Pass a function, not a string:

var crd = plugin().ClickSimMove();
setTimeout(function() {
    plugin().ClickSimClick(crd[0], crd[1]);
}, 1000);

When you pass a string, it's evaluated as it would be with eval in the global scope, losing all access to local variables. An anonymous function lets you reference any variable in scope.

Upvotes: 2

Related Questions