setTimeout () method is used to evaluate the expression or function call after the specified number of milliseconds, while setInterval () is in the specified number of milliseconds every cycle calling function or expression, clearInterval until it clears. That setTimeout () only once, setInterval () can be executed multiple times. The same parameters of the two functions, the first parameter is the code or handler to be executed, and the second is the number of milliseconds delay.
setTimeOut Usage
Using setTimeout function is as follows:
var timeoutID = window.setTimeout(func, [delay, param1, param2, ...]);
var timeoutID = window.setTimeout(code, [delay]);
timeoutID: timer ID, it can clearTimeout () function is used to clear the timer.
func: the function to be executed.
code :( alternative syntax) a code string to be executed.
delay: delay time, in milliseconds. If not specified, the default is 0.
We can use window.setTimeout or setTimeout, both essentially the same wording, but window.setTimeout the setTimeout function as an attribute to the global window object reference.
Application examples:
function timeout(){
document.getElementById('res').innerHTML=Math.floor(Math.random()*100 + 1);
}
setTimeout("timeout()",5000);
When the code is executed, after five seconds call timeout () function, click on to .
setInterval Usage
Parameters and usage setInterval and setTimeout functions functions, refer to setTimeout function described above usage. The difference is, setInterval regular intervals among the func or code execution of code.
Application examples:
var tt = 10;
function timego(){
tt--;
document.getElementById("tt").innerHTML = tt;
if(tt==0){
window.location.href='/';
return false;
}
}
var timer = window.setInterval("timego()",1000);
Function timego () defines the content of the page elements #tt displayed when tt is equal to 0, the page orientation to the home. We then define a timer timer, use setInterval () is called once every 1 second timego (). Such timego performs 10 times digital tt will be reduced by 1 until zero. So if you want to stop the timer, you can use the following code:
window.clearInterval(timer);
When the code is executed, after 10 seconds the page will jump to the home page, click on to .
In fact setTimeout () can also be implemented from time to time to repeat a function, but we simply use setTimeOut difference and setInterval. In addition to single-threaded manner javascript is running on the browser's javascript engine, the actual application of complex tasks need to line up to perform, which may cause the timer time allowed, the question needs to be considered in large applications, this article does not give in-depth study.