开发者

How to make Javascript timer work for variable parameter

开发者 https://www.devze.com 2023-03-14 17:11 出处:网络
The Javascript tim开发者_开发百科er event has this basic syntax: var t=setTimeout(\"javascript statement\",milliseconds);

The Javascript tim开发者_开发百科er event has this basic syntax:

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

I have this function that gets called onkeyup() for some text box. I want the numeric_value_search() function to be called after a certain amount of time, which is 5 seconds in this example.

The key line is the 5th line. I have four different ways that it might be written, each of which gives the specified error:

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

ERROR: useless setTimeout call (missing quotes around argument?)

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

ERROR: boundBox is not defined

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

ERROR: missing ] after element list

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

ERROR: data is passed nicely and there are no explicit errors but the timer doesn't work

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


As @kgiannakakis already said,

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

is the way to go.

The reason is simple: When using a string argument it's like using eval() which is usually evil. When passing a function however you not only avoid putting code inside a string (which breaks syntax highlighting and might require escape orgies) but also have the possibility of using a closure to access variables in the current context without embedding them into a string (which might lead to code injection if not done properly).


Try this:

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

精彩评论

暂无评论...
验证码 换一张
取 消