0

I'm trying to push elements into array X while iterating through array Y. At some point, while pushing a new element into array X, I get an "Unexpected token :" error in the browser console. I am able to push several elements properly before it fails (almost every time around 7th element).

It is recursive function, and maybe that causes an issue... Here is the code:

function getPosition(img) {
    var tmpRandPosition = Math.floor(Math.random() * (9));

    if($.inArray(galleryPositions[tmpRandPosition], populatedPositions) != -1) {
        setTimeout("getPosition("+img+")",1);
    } else {
        populatedPositions.push(galleryPositions[tmpRandPosition]);

        return true;
    }
}

As you can see from the script, I'm trying to display photos randomly at 8 different positioned elements in HTML.

SethO
  • 2,703
  • 5
  • 28
  • 38
jMn
  • 238
  • 1
  • 3
  • 11
  • I think, its more likely that there is a problem with the filename of that particular image or something like that. Oh, and pass a function instead of a string to that setTimeout. – Christoph May 10 '12 at 14:22
  • The problem was, as @antyrat pointed, in wrong function passing from setTimeout(). – jMn May 10 '12 at 14:35

3 Answers3

3

Seems the problem is in the setTimeout function. Try to pass the argument to that function using an anonymous function instead of concatenation:

setTimeout(function() { getPosition(img) }, 1);
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
antyrat
  • 27,479
  • 9
  • 75
  • 76
2

This will break:

setTimeout("getPosition("+img+")",1);

as it actually writes:

setTimeout("getPosition(img_path.jpg)",1);

and tries to evaluate it (using eval).

The problem is that JS consider img_path.jpg as a variable.

Fix:

setTimeout("getPosition('"+img+"')",1);

But never do it this way as it's not good or fast to evaluate a string.

Send instead an anonymous function to setTimeout:

REALFIX:

setTimeout(function() {
    getPosition(img);
}, 1);
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
1

Don't call setTimeout with a string argument. Always use a function. Using the string in this case subjects this code to injection attacks if the img variable is vulnerable.

Community
  • 1
  • 1
Will
  • 6,601
  • 3
  • 31
  • 42