【问题标题】:Refresh JS function with variables用变量刷新 JS 函数
【发布时间】:2017-03-17 13:05:05
【问题描述】:
function checkDownload(a, b) {
    var number = a;
    var id = b;

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

所以问题是,setTimeout 出现错误(找不到变量号)....但是为什么呢?我只想在 5 秒后用我之前得到的变量刷新函数。

问候

【问题讨论】:

标签: javascript jquery


【解决方案1】:

所以认为,在 setTimeout 出现错误(找不到变量号)....但是为什么呢?

因为当您使用带有setTimeout 的字符串时,该字符串中的代码会在全局范围内进行评估。如果您没有 global 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-14
    • 2021-12-12
    相关资源
    最近更新 更多