Mohan Ram Mohan Ram - 2 years ago 155
Javascript Question

To delay JavaScript function call using jQuery



function sample() {
alert("This is sample function");

t = setTimeout("sample()",2000);



<input type="button" id="button" value="Call sample function with delay">

Once I click the button,
function is not called with a delay of 2 seconds. I don't know what's wrong.

How to call JavaScript function using
via jQuery?

Answer Source

Since you declare sample inside the anonymous function you pass to ready, it is scoped to that function.

You then pass a string to setTimeout which is evaled after 2 seconds. This takes place outside the current scope, so it can't find the function.

Only pass functions to setTimeout, using eval is inefficient and hard to debug.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download