Method 1. Apply jQuery extension to solve this problem.
Copy codeThe Code is as follows: $ (document). ready (function (){
$. Extend ({
Show: function (){
Alert ("ready ");
}
});
SetInterval ("show ()", 3000 );
});
Method 2: Do not use quotation marks or parentheses when specifying the function to be executed regularly.
Copy codeThe Code is as follows: $ (function (){
Function show (){
Alert ("ready ");
}
SetInterval (show, 3000); // note that the function name is not enclosed in quotation marks or arc!
// When setInterval ("show ()", 3000) is used, "an object is missing" is reported"
});
Differences:
SetTimeout ()
Execute an expression or function at the specified time after loading;
Run only once. It is used with window. clearTimeout.
SetInterval ()
During execution, it executes an expression or function at a specified time after loading the page; (the function is similar to a recursive function); it is used with window. clearInterval.
Note:
Both methods can be used to execute JavaScript after a fixed period of time. However, they have different application scenarios.
Method
In fact, setTimeout and setInterval have the same syntax. They both have two parameters: one is the code string to be executed, and the other is the interval in milliseconds. after that period, the code will be executed.
However, there are differences between the two functions. After the setInterval code is executed, it will automatically re-execute the code at that fixed interval, setTimeout only executes the code once.
Although it seems that setTimeout can only be applied to on-off actions, you can call setTimeout repeatedly by creating a function loop to implement repeated operations:
Copy codeThe Code is as follows: showTime ();
Function showTime ()
{
Var today = new Date ();
Alert ("The time is:" + today. toString ());
SetTimeout ("showTime ()", 5000 );
}
Once this function is called, the time is displayed every five seconds. If setInterval is used, the corresponding code is as follows:
Copy codeThe Code is as follows: setInterval ("showTime ()", 5000 );
Function showTime ()
{
Var today = new Date ();
Alert ("The time is:" + today. toString ());
}
The two methods may look very similar and show similar results, but the biggest difference between the two is that the setTimeout method does not execute the showTime function every five seconds, it executes the showTime function five seconds after each setTimeout call. This means that if the main part of the showTime function needs to be executed in 2 seconds, the whole function will be executed every 7 seconds. While setInterval is not bound by the function called by itself, it simply repeats the function at a certain time.
If you want to execute an action accurately after a fixed interval, you 'd better use setInterval. If you don't want to interfere with each other due to continuous calls, in particular, each function call requires heavy computing and a long processing time, so it is best to use setTimeout.