Home > Web Front-end > JS Tutorial > body text

What is the difference between settimeout and setinterval?

青灯夜游
Release: 2020-11-11 15:01:17
Original
38062 people have browsed it

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.

What is the difference between settimeout and setinterval?

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');
Copy after login

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);//参数是函数名
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!