Let's use examples to illustrate several methods of setTimeout in jQuery. First, we have prepared the DIV and public functions used for testing:
Copy codeThe Code is as follows:
<Div id = "div_debug"> </div>
<Script src = "http://www.studyday.net/demo/jquery.js"> </script>
<Script language = "JavaScript">
Functionlog (s ){
$ ('# Div_debug'). append (s + '<br> ');
}
// The code for trial use in the following section can be placed under this line of comment, replace it //...
//...
</Script>
The basic usage of setTimeout in the original javascript is like this.
Copy codeThe Code is as follows:
// Basic setTimeout usage in original javascript
FunctionfunA (){
Log ('funa ...');
SetTimeout ('funa () ', 1000 );
}
FunA ();
The following are some usage methods of setTimeout in jQuery: Online instances.
Copy codeThe Code is as follows:
// JQuery usage
FunctionfunA (){
Log ('funa ...');
SetTimeout ('funa () ', 1000 );
}
JQuery (document). ready (function ($ ){
// Usage 1: Write the function to be called out of ready to make it a global function.
FunA ();
// Usage 2: Write the function name directly, without parentheses or quotation marks. This method is suitable for functions without parameters.
FunctionfunB (){
Log ('funb ...');
SetTimeout (funB, 1000 );
}
FunB ();
// Usage 3: it is suitable for functions with parameters to be executed by calling anonymous functions.
FunctionfunC (v ){
Log ('func... '+ v );
SetTimeout (function () {funC (v + 1)}, 1000 );
}
FunC (1 );
// Usage 4: by adding a function to the jQuery namespace, the 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 wider than usage 3? The following example shows the differences between the two:
Copy codeThe Code is as follows:
JQuery (document). ready (function ($ ){
// Usage 3: it is suitable for functions with parameters to be executed by calling anonymous functions.
FunctionfunC (v ){
Log ('func... '+ v );
SetTimeout (function () {funC (v + 1)}, 1000 );
}
// Usage 4: It is easier to call by adding a function to the jQuery namespace
$. Extend ({
FunD: function (v ){
Log ('Fund... '+ v );
SetTimeout ("$. funD (" + (v + 1) + ")", 1000 );
}
});
});
JQuery (document). ready (function ($ ){
// FunC (1); // if this sentence is executed after the annotation is removed, an error is returned.
$. FunD (100); // This sentence is normal. Understand the difference between the two.
});