0

Alright I have a feeling this is simple and I'm overlooking something.

I have an array of data that I'm passing into the function containing 300 rows. The function itself picks out a random box to update, and a random array element to pass (0-299) and then updates that box.

The first Iteration is fine. The second returns "Uncaught ReferenceError: rand_ad is not defined "

function loop(last_ad, last_ad_box, ads_array){

        // start
        while(rand_ad == last_ad){
               var rand_ad = get_rand(299);
        }
        while(rand_ad_box == last_ad_box){
               var rand_ad_box = get_rand(29);
        }

        console.log(ads_array[rand_ad]);
        // update the ad
        // update_ad('.addno-'+rand_ad_box, ads_array[rand_ad]);

        //recall itself to continue looping after 1 second
        t = setTimeout("loop(rand_ad, rand_ad_box, ads_array)",3000);
    }
    function get_rand(max){
        var rand = Math.floor(Math.random()*max) + 1;   
        return rand;
    }

I think it might be the quotation marks around the function loop, that it's treating the variables inside as strings instead of actual variables, but I can't get it to render out before it snaggs the error.

Any ideas?

2
  • You need to define your variables before they are called. At the beginning of your function, add: var rand_ad_box, rand_ad. Commented Jan 23, 2014 at 1:20
  • It would trip though on the first loop if they were undefined to begin with. It runs the first iteration just fine, only after the loop does it mess up Commented Jan 23, 2014 at 1:22

1 Answer 1

3

Your guess is correct. Change the timeout line to this:

t = setTimeout(loop, 3000, rand_ad, rand_ad_box, ads_array);

Passing strings to setTimeout is a security risk and not recommended. Also, it doesn't execute the code until the timeout occurs, so the variables are dereferenced after the function has exited.

If you need it to work in IE, then you'll have to use this:

t = setTimeout(function () {
    loop(rand_ad, rand_ad_box, ads_array);
}, 3000);
Sign up to request clarification or add additional context in comments.

4 Comments

Don't forget that rand_ad and others are free variables
Yep, that did the trick. I'd buy ya a beer if you were here haha. Bout ready to throw my keyboard. Thanks much!
Think if you're a newbie (point wise) it takes a while before you can accept an answer ... but here's an upvote for you :)
It was making me wait 5 min ;) otherwise I'd have done it already

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.