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?

Community
  • 1
  • 1
Mohan Ram
  • 8,345
  • 25
  • 81
  • 130

3 Answers3

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)
Starx
  • 77,474
  • 47
  • 185
  • 261
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 3
    ...or wrap to your liking: `setTimeout( function() { myBarFunction('whatever','parameter', 123)}, 2000 ); – Frank N Dec 15 '14 at 16:42
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() { ... })().

alex
  • 479,566
  • 201
  • 878
  • 984
20

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)
Fizzix
  • 23,679
  • 38
  • 110
  • 176