Javascript setTimeout() function jquery examples and chaining it with afterTime() plugin

jquery_logo

javascript setTimeout() function

  • It takes two arguments.
    1. Callback function to execute after milliseconds supplied.
    2. Milliseconds – after how many milliseconds, callback function will execute?.
  • It’s asynchronous or non-blocking.

    i.e. next line after setTimeout executes immediately and doesn’t wait for callback to execute.

  • It returns a handler that can be used to halt execution of setTimeout() function.
    handler = setTimeout(callback,2000);
    clearTimeout(handler); // cancels execution of callback after 2s.

jQuery setTimeout() usage example

$(document).ready(function () {
    $('#btn').on('click', function () {
        setTimeout(function () {
            alert("button clicked");
        }, 2000);
    });
});

Button Code:-

<div id="content">
    <input type="button" id="btn" value="Alert after 2 seconds" />
</div>

Output:-

jQuery afterTime() method to chain setTimeout() function

jQuery afterTime() method can be used to chain with jQuery selectors

jQuery.fn.extend({
    afterTime: function (sec, callback) {
        that = $(this);
        setTimeout(function () {
            callback.call(that);
        }, sec);
        return this;
    }
});

Sample Usage of this plugin

$(document).ready(function () {
    $('#content').append("Dom Ready.<br/>").afterTime(2000, function () {
        $(this).append("This will appear after 2 secs.<br/>")
    });
});

Demo

Further Chaining:-  it executes jQuery append() without waiting for afterTime() callback to finish.

$(document).ready(function () {
    $('#content').append("Dom Ready.<br/>").afterTime(2000, function () {
        $(this).append("This will appear after 2 secs.<br/>")
    }).append('This will appear without timer.<br/>');;
});

Demo

 Chaining of afterTime() method to execute multiple setTimeout() synchronously.

$(document).ready(function(){
    $('#content').append("Dom Ready.<br/>").afterTime(3000,function(){
        $(this).append("This will appear after 3 secs.<br/>");
            $(this).afterTime(2000,function(){
                $(this).append("This will appear after 5 secs.");    
            });
    });
});

 Demo

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

 
Previous Post

Flat UI – Simple HTML tabs without jQuery or any other library

Next Post

How to style HTML form fields using CSS 3 linear-gradient() function?

Related Posts