In the last post of jquery, we learn how to create a generic jquery code to validation complete site. Now will learn how to Delay function or Method execution for some time with SetTimOut Function after Jquery ready method.
Sometimes we have to delay execution of the method for some time or want to execute method continuously after a fix time interval using java script. i.e. want to create clock or do a service call. In any of these situations, we will user java script setTimeOut function.
SetTimeOut function takes two arguments.
1. First is code that needs to execute. You can place a method name or code statements here.
2. Second is time interval after you want to execute this method.
jQuery(document).ready(function(){ setTimeout("DoAnyWork()", 1000); // or use anonymous functions instead setTimeout(function() { alert('Hi') }, 1000) });
DoAnyWork is the name of the function you want to execute after one second. You can place any code statements also here i.e.
jQuery(document).ready(function(){ setTimeout("var message='Test Message';alert('Test alert');", 1000); });
Note 1: Using the Second version is not recommended, it causes problems with minifications. It’s here mainly for compatibility with older JavaScript code.
Note 2: Above code will continue to execute after every 1 Sec. If you want to cancel this process than can use clearTimeout method as below statement.
vartimerId = setTimeout(function() { alert(1) }, 1000); clearTimeout(timerId)