Let’s use examples to illustrate several ways to use setTimeout in jQuery. First, prepare the DIV and public functions for testing:
< /div>
The basic usage of setTimeout in original javascript is like Something like this.
//Basic usage of setTimeout in original javascript
functionfunA(){
log('funA...');
setTimeout('funA()', 1000);
}
funA();
The following are several ways to use setTimeout in jQuery. Online examples
//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 parentheses Quotes are not allowed, 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 Guang
$.extend({
funD:function(v){
log('funD...' v);
setTimeout("$.funD(" (v 1) ") ",1000);
}
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? Through the following example, you can intuitively understand the difference between the two. Difference:
Copy code
The code is as follows:
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: Through the jQuery namespace Add functions to make it more convenient to call
$.extend({
funD:function(v){
log('funD...' v);
setTimeout("$.funD( " (v 1) ")",1000);
/funC(1); //When executing this sentence after removing the comment, an error will be reported
$.funD(100); //This sentence is normal. Do you understand the difference between the two?
});