Home > Article > Web Front-end > What is the difference between settimeout and setinterval?
Difference: setTimeout only runs once, which means that the specified code will be triggered to run when the set time is up, and it will end after running; while etinterval will run in a loop, that is, every time the set time interval is reached, it will run Trigger the specified code. To stop, you need to use the clearInterval() function.
The difference between settimeout and setinterval
1. SetTimeout and setInterval are both timers in JS and can be specified Delay time before performing an operation. The difference is that setTimeout stops after performing an operation after the specified time; while setInterval can keep looping. If you want to stop, you can use window.clearInterval( );
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 calling 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 stop running; while setInterval will pop up 'hello' every one second until cleared with clear Timer syntax.
For more programming-related knowledge, please visit: Introduction to Programming! !
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!