46

JavaScript:

$(document).ready(function(){
    
    function sample() {
       alert("This is sample function");
    }
 
    $("#button").click(function(){
        t = setTimeout("sample()",2000);
    });
        
});

HTML:

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

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

How to call JavaScript function using setTimeout() via jQuery?

2
  • 1
    You should have seen something like sample is not defined on the console. Commented Mar 16, 2011 at 7:54
  • @Felix Kling, If you were mentioning to me, I could see a sample defined. Commented Mar 16, 2011 at 8:05

3 Answers 3

88

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.

setTimeout(sample,2000)
Sign up to request clarification or add additional context in comments.

1 Comment

...or wrap to your liking: `setTimeout( function() { myBarFunction('whatever','parameter', 123)}, 2000 );
36
function sample() {
    alert("This is sample function");
}

$(function() {
    $("#button").click(function() {
        setTimeout(sample, 2000);
    });

});

jsFiddle.

If you want to encapsulate sample() there, wrap the whole thing in a self invoking function (function() { ... })().

Comments

21

Very easy, just call the function within a specific amount of milliseconds using setTimeout()

setTimeout(myFunction, 2000)

function myFunction() {
    alert('Was called after 2 seconds');
}

Or you can even initiate the function inside the timeout, like so:

setTimeout(function() {
    alert('Was called after 2 seconds');
}, 2000)

Comments

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.