0
function checkDownload(a, b) {
    var number = a;
    var id = b;

    //NOT RELATED CODE....
    setTimeout("checkDownload(number,id)", 5000);
}
checkDownload("test", "test1");

So the thing is, at the setTimeout an Error comes with (Cannot find variable number).... But why? I only want to refresh the function after 5 seconds with the variable I got before.

Regards

nashcheez
  • 5,067
  • 1
  • 27
  • 53
Lena Luther
  • 23
  • 1
  • 3
  • 1
    Duplicate of [*Is there ever a good reason to pass a string to setTimeout?*](http://stackoverflow.com/questions/6081560/is-there-ever-a-good-reason-to-pass-a-string-to-settimeout)? The question itself mentions the string version using globals... – T.J. Crowder Mar 17 '17 at 13:09

1 Answers1

9

So the think is, at the setTimeout an Error comes with (Cannot find variable number).... But why?

Because when you use a string with setTimeout, the code in that string is evaluated at global scope. If you don't have global number and id variables, you'll get an error.

Don't use strings with setTimeout and setInterval, use functions:

// On any recent browser, you can include the arguments after the timeout and
// they'll be passed onto the function by the timer mechanism
setTimeout(checkDownload, 5000, number, id);

// On old browsers that didn't do that, use a intermediary function
setTimeout(function() {
    checkDownload(number, id);
}, 5000);
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875