Home >Web Front-end >JS Tutorial >What is the difference between setTimeout and setInterval

What is the difference between setTimeout and setInterval

hzc
hzcOriginal
2020-06-28 13:30:466520browse

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. .

What is the difference between setTimeout and setInterval

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!

Statement:
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