javascript setTimeout() function
- It takes two arguments.
- Callback function to execute after milliseconds supplied.
- 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."); }); }); });