[javascript] To delay JavaScript function call using jQuery

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?

This question is related to javascript jquery

The answer is


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)

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() { ... })().