如何使Javascript定时器为变量参数工作

How to make Javascript timer work for variable parameter

本文关键字:变量 参数 工作 定时器 何使 Javascript      更新时间:2023-09-26

Javascript计时器事件具有以下基本语法:

var t=setTimeout("javascript statement",milliseconds);

我有一个函数,它被调用为一些文本框的onkeyup()。我希望在一定时间后调用numeric_value_search()函数,在本例中为5秒。

关键的一行是第五行。我有四种不同的写法,每种写法都会给出指定的错误:

    timer=setTimeout(numeric_value_search(boundBox),5000);

错误:无用的setTimeout调用(参数周围缺少引号?)

    timer=setTimeout("numeric_value_search(boundBox)",5000);

错误:未定义边界框

    timer=setTimeout("numeric_value_search("+boundBox+")",5000);

错误:元素列表后缺少]

    timer=setTimeout(numeric_value_search("+boundBox),5000);

错误:数据传递得很好,没有明显的错误,但计时器不工作

var timer;
function chk_me(boundBox){
console.info(boundBox.id);
    clearTimeout(timer);
//  --- timer code here ---   e.g. timer=setTimeout("numeric_value_search("+boundBox+")",5000);
}

正如@kgiannakakis已经说过的,

setTimeout(function() {
    numeric_value_search(boundBox);
}, 5000);

是要走的路。

原因很简单:当使用字符串参数时,它就像使用eval(),这通常是邪恶的。然而,在传递函数时,您不仅可以避免将代码放在字符串中(这会破坏语法高亮显示,可能需要转义狂欢),还可以使用闭包访问当前上下文中的变量,而不将它们嵌入字符串中(如果操作不当,可能会导致代码注入)。

试试这个:

setTimeout(function() {
    numeric_value_search(boundBox);
}, 5000);