0

The Javascript timer 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);
}

2 Answers 2

3

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).

Sign up to request clarification or add additional context in comments.

Comments

2

Try this:

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

1 Comment

+1, this is the only way to use setTimeout which is both correct and clean.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.