.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> JQuery >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

how to use setTimeout function in jquery

Posted By:JQuery Developer       Posted Date: May 20, 2013    Points: 40    Category: JQuery    URL: http://www.dotnetspark.com  

In this JQuery code example we will see how to use setTimeout() function using JQuery in our web site
 

As we all know that setTimeout() is javascript method to call a function or code after a specified number of milliseconds. In other word if you want to execute a javacript method for a regular interval you should use setTimeout() method. In JQuery too we can make use of setTimeout() method.

Lets see how to use. In below example I am just appending the count to a text after every second.

// Declare global variable
var count = 1; 

// Function to update the dive text counter
function updateDiv() {
    // your logic/ work goes here 
    // In below code I am just appending counter text
    $("#myDiv").append(count);
    setTimeout(updateDiv, 1000);
    // Increment the global variable
    count += 1;
}

and call the updateDiv() from document.ready like below

$(document).ready(function () {
    updateDiv(); 
});

Html code for div tag

<div id="myDiv">Timer: </div>

 

Click here for live demo

Full html and JQuery code with setTimeout() used in above example

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <script type="text/javascript">

        $(document).ready(function () {
            updateDiv();
        });

        // Declare global variable
        var count = 1;

        // Function to update the dive text counter
        function updateDiv() {
            // your logic/ work goes here 
            // In below code I am just appending counter text
            $("#myDiv").append(count);
            setTimeout(updateDiv, 1000);
            // Increment the global variable
            count += 1;
        }

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="myDiv">
        Timer:
    </div>
    </form>
</body>
</html>

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend