Method 1. Applying jQuery extension can solve this problem.
Difference:
setTimeout()
Delay the specified time from loading to execute an expression or function;
Execute only once; used together with window.clearTimeout.
setInterval()
When executing, it executes an expression or function at specified intervals after loading the page; (function is similar to a recursive function); used together with window.clearInterval.
Additional instructions:
Both methods can be used to execute JavaScript after a fixed period of time. However, both have their own application scenarios.
Method
Actually, the syntax of setTimeout and setInterval are 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 which the code will be executed.
However, there is a difference between the two functions. After executing the code once, setInterval will automatically execute the code repeatedly after the fixed time interval, 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 to repeatedly call setTimeout to achieve repeated operations:
Once this function is called, the time will be displayed every 5 seconds. If you use setInterval, the corresponding code looks like this:
These two methods may look very similar, and the displayed results will be very similar, but the biggest difference between the two is that the setTimeout method does not execute the showTime function every 5 seconds, it does so every time Execute the showTime function 5 seconds after calling setTimeout. This means that if the main part of the showTime function takes 2 seconds to execute, then the entire function will only execute every 7 seconds. However, setInterval is not bound by the function it calls. It simply executes that function repeatedly at a certain time.
If you need to perform an action accurately after every fixed time interval, then it is best to use setInterval. If you do not want to cause mutual interference due to continuous calls, especially each function call needs to Heavy calculations and long processing time, then it is better to use setTimeout.