setTimeout()
Delay the specified time from loading to execute an expression or function;
Execute only once; used together with window.clearTimeout.
I Copy the code in
$(document).ready(function (){
setTimout(test(),200);
function test()
{
alert(1);
}
});
will only be executed once. Some friends said that you can use
setInterval ("showTime()", 5000);
function showTime()
{
var today = new Date();
alert("The time is: " today.toString ());
}
But I can also call the following method the same as setInterval
Several ways to use setTimeout in jQuery
setTimeout/setInterval in jQuery cannot be used like in the original javascript, otherwise an error will be reported.
Let's use examples to illustrate several ways to use setTimeout in jQuery. First, prepare the DIV and public functions for testing:
The basic usage of setTimeout in original javascript is like this.
//Basic usage of setTimeout in original javascript
functionfunA(){
log('funA.. .');
setTimeout('funA()', 1000);
}
funA();
The following are several uses of setTimeout in jQuery Method. Online example
//Usage in jQuery
functionfunA(){
log('funA...');
setTimeout('funA()', 1000);
}
jQuery(document).ready(function($){
//Usage 1: Write the function to be called outside ready, making it a global function
funA();
//Usage 2: Write the function name directly, without brackets or quotes, suitable for functions without parameters
functionfunB(){
log('funB...');
setTimeout(funB, 1000);
}
funB();
//Usage 3: Executed by calling an anonymous function, suitable for functions with parameters
functionfunC(v){
log('funC...' v);
setTimeout(function(){funC(v 1)}, 1000);
}
funC(1);
//Usage 4: By adding functions to the jQuery namespace, the scope of application is wider
$.extend({
funD:function(v){
log('funD...' v) ;
setTimeout("$.funD(" (v 1) ")",1000);
}
});
$.funD(100);
});
The difference between Usage 2 and Usage 3 is obvious, but what is the difference between Usage 3 and Usage 4? Why is Usage 4 more widely applicable than Usage 3? Take the following example You can intuitively understand the difference between the two:
jQuery(document).ready(function($){
//Usage 3: Executed by calling an anonymous function, suitable for functions with parameters
functionfunC(v){
log('funC. ..' v);
setTimeout(function(){funC(v 1)}, 1000);
}
//Usage 4: By adding a function to the jQuery namespace, call It is more convenient
$.extend({
funD:function(v){
log('funD...' v);
setTimeout("$.funD(" (v 1) ")",1000);
}
});
});
jQuery(document).ready(function($){
//funC(1) ; //When executing this sentence after removing the comment, an error will be reported
$.funD(100); //This sentence is normal, understand the difference between the two
});