0

I seem to be unable to pass parameter to an anonymous function as the argument of a setTimeOut call. Here is the code

http://jsfiddle.net/5xg5d6pp/

var arr = ["Just a test","I miss you so much darling #$%&%@;..\]]/"];

console.log(arr);
for(var c=0; c < arr.length; c++){
    console.log(arr[c]);

    //wait 1 sec for next loop
    setTimeout(function(arr[c]) {
        do_magic(arr[c]);
    }, 1000);
}

function do_magic (passed_var){
    console.log(passed_var);
}
giorgio79
  • 3,787
  • 9
  • 53
  • 85
  • `Uncaught SyntaxError: Unexpected token [ `.... – davidkonrad Feb 09 '15 at 12:21
  • Yes, because I added the parameter in the anonymous function...If I remove it, the code works, but then I dont get arr[c] values at all inside the function. – giorgio79 Feb 09 '15 at 12:22
  • 3
    possible duplicate of [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Andreas Feb 09 '15 at 12:22
  • Lol the solution there seems a bit convoluted... – giorgio79 Feb 09 '15 at 12:28

1 Answers1

0

When you do this setTimeout(function(arr[c]) { You are defining a new function and saying that I want this function to accept a parameter called 'arr[c]', you aren't saying that you want to pass arr[c] to it and because you can't have any special characters in the name of a parameter you get an error. What you should do is define a function outside of the loop to avoid the loop closure issue and pass the parameter to that letting that function create the setTimeout for you. Please see JavaScript closure inside loops – simple practical example for more information about closures. Also read this to learn more about javascript functions: http://javascript.info/tutorial/functions-declarations-and-expressions

This is the correct code below:

var arr = ["Just a test","I miss you so much darling #$%&%@;..\]]/"];

console.log(arr);
for(var c=0; c < arr.length; c++){
    console.log(arr[c]);

    setTimeoutFactory(arr[c]);
}

function do_magic (passed_var){
    console.log(passed_var);
}

function setTimeoutFactory(text) {
setTimeout(function() {
        do_magic(text);
    }, 1000);
}
Community
  • 1
  • 1
Gabriel Sadaka
  • 1,748
  • 1
  • 15
  • 19