Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 255
Mohan Ram Avatar asked Mar 16 '11 07:03

Mohan Ram


People also ask

How do you delay a function in JavaScript?

To delay a function call, use setTimeout() function. functionname − The function name for the function to be executed. milliseconds − The number of milliseconds. arg1, arg2, arg3 − These are the arguments passed to the function.

What is the use of delay () method in jQuery?

jQuery delay() Method The delay() method sets a timer to delay the execution of the next item in the queue.

Is delay event method in jQuery?

The delay() is an inbuilt method in jQuery which is used to set a timer to delay the execution of the next item in the queue. para1: It specifies the speed of the delay. para2: It is optional and specifies the name of the queue.

How do you call a function with a delay?

Answer: To delay a function call, use setTimeout() function. function-name − The function name for the function to be executed.


3 Answers

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)
like image 153
Quentin Avatar answered Oct 17 '22 22:10

Quentin


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

like image 36
alex Avatar answered Oct 17 '22 23:10

alex


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)
like image 19
Fizzix Avatar answered Oct 17 '22 22:10

Fizzix