Let's illustrate several ways to use settimeout in jquery by example, and first prepare the div and common functions for testing:
Copy Code code 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 used in the following test can be placed below this line of comments, replacing//...
//...
</script>
The basic usage of settimeout in native JavaScript is like this.
Copy Code code as follows:
Basic usage of settimeout in original ecological javascript
Functionfuna () {
Log (' Funa ... ');
SetTimeout (' Funa () ', 1000);
}
Funa ();
Here are several ways to use settimeout in jquery. Online example
Copy Code code as follows:
The usage in JQuery
Functionfuna () {
Log (' Funa ... ');
SetTimeout (' Funa () ', 1000);
}
JQuery (document). Ready (function ($) {
Usage 1: Write the function to be called outside the ready, making it a global function
Funa ();
Usage 2: Write function names directly, not with parentheses or quotes, for functions without parameters
Functionfunb () {
Log (' Funb ... ');
SetTimeout (FUNB, 1000);
}
Funb ();
Usage 3: Execute by calling 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 application is broader
$.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 where is the difference between usage 3 and usage 4? Why is the usage 4 more extensive than the usage 3? The following example makes it intuitive to understand the difference between the two:
Copy Code code as follows:
JQuery (document). Ready (function ($) {
Usage 3: Execute by calling anonymous function, suitable for functions with parameters
Functionfunc (v) {
Log (' FunC ... ' +v);
settimeout (function () {FunC (v+1)}, 1000);
}
Usage 4: It's 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); When you remove a comment, the error occurs when you execute this sentence
$.fund (100); This sentence is normal, understand the difference between the two
});