Method 1. Applying jQuery extensions can solve this problem.
$(document).ready(function(){
$.extend({
show:function(){
alert("ready");
}
});
setInterval("show()",3000);
});
Method 2. Do not use quotes and brackets when specifying functions executed at a time.
$(function(){
function show(){
alert("ready");
}
setInterval(show,3000);// Note that the function name has no quotes and brackets!
// Using setInterval("show()",3000); will report "Missing object"
});
the difference:
setTimeout()
Execute an expression or function from the specified time after loading;
Execute only once; and use together.
setInterval()
When executing, it executes an expression or function at a specified time from the page loading; (function is similar to a recursive function); and use it together.
Additional Notes:
Both methods can be used to implement JavaScript execution after a fixed time period. However, both have their own application scenarios.
method
In fact, the syntax of setTimeout and setInterval is the same. They all have two parameters, one is the code string to be executed, and the other is the time interval in milliseconds. After that time period, that piece of code will be executed.
However, there is still a difference between these two functions. After setInterval executes the code once, after that fixed time interval, it will automatically execute the code repeatedly, while setTimeout only executes that code once.
Although on the surface it seems that setTimeout can only be applied to on-off actions, you can create a function loop and repeatedly call setTimeout to achieve repeated operations:
showTime();
function showTime()
{
var today = new Date();
alert("The time is: " + ());
setTimeout("showTime()", 5000);
}
Once this function is called, the time will be displayed every 5 seconds. If you use setInterval, the corresponding code looks like this:
setInterval ("showTime()", 5000);
function showTime()
{
var today = new Date();
alert("The time is: " + ());
}
These two methods may look very similar, and the displayed results will also be very similar. However, the biggest difference between the two is that the setTimeout method does not execute the showTime function every 5 seconds. It executes the showTime function after 5 seconds after each call setTimeout. This means that if the body part of the showTime function takes 2 seconds to execute, the entire function will only be executed every 7 seconds. However, setInterval is not bound by the function it calls. It simply executes the function repeatedly every certain time.
If you require a certain action to be executed accurately after a fixed time interval, it is best to use setInterval, and if you do not want to interfere with each other due to continuous calls, especially when each function call requires heavy calculations and a long processing time, it is best to use setTimeout.