2017-03-17 60 views
0
function checkDownload(a, b) { 
    var number = a; 
    var id = b; 

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

所以事情是,在setTimeout错误(无法找到变量号码)....但为什么?我只想在5秒后用我之前得到的变量刷新该函数。刷新变量的JS功能

问候

+1

的重复[*是否有过一个很好的理由来传递一个字符串给setTimeout的*?](http://stackoverflow.com /问题/ 6081560/IS-有有史以来-A-好理由对传递一个字符串到setTimeout的)?这个问题本身提到了使用全局变量的字符串版本... –

回答

9

因此认为,在setTimeout的错误自带(找不到变量个数)......但是,为什么?

因为当您使用字符串setTimeout时,该字符串中的代码将在全局范围内进行评估。如果您没有全球numberid变量,您将收到错误消息。

不要使用字符串与setTimeoutsetInterval,使用功能:

// 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); 
+2

打败了我。有一个工作小提琴:https://jsfiddle.net/L286s259/ –