Home > Article > Web Front-end > What is the difference between setTimeout and setInterval
setTimeout and setInterval are both timers in JS. You can specify a delay time before performing an operation. The difference is that setTimeout stops after performing an operation after the specified time, while setInterval can continue to loop. .
1. Both setTimeout and setInterval are timers in JS. They can specify a delay time before performing an operation. The difference is that setTimeout stops after performing an operation after the specified time, while setInterval can continue to loop.
function fun(){ alert('hello'); } setTimeout(fun,1000);//参数是函数名 setTimeout('fun()',1000);//参数是字符串 setInterval(fun,1000); setInterval('fun(),1000');
In the above code, whether it is setTimeout or setInterval, parameters cannot be taken when using the function name as the calling handle, but parameters can be taken when calling using a string. For example: setTimeout('fun(name)',1000);
2. Instead of defining a separate function, place the function call directly in a function. You can use the function name as the call handle.
function fun(name){ alert('hello'+' '+name); } setTimeout (function(){ fun('Tom'); },1000);//参数是函数名
In the above code, the difference between setTimeout and setInterval is that setTimeout will pop up 'hello' after one second, and then it will not run again; while setInterval will pop up 'hello' every one second until it is used. clear syntax to clear the timer.
Recommended tutorial: "JS Tutorial"
The above is the detailed content of What is the difference between setTimeout and setInterval. For more information, please follow other related articles on the PHP Chinese website!