javascript setTimeout() 和 setInterval() 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22825326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:50:35  来源:igfitidea点击:

difference between setTimeout() and setInterval()

javascript

提问by AL-zami

i am trying to move a small div along a big div in the y-direction according to how much i scrolled down the page.but i've found that using setTimeout() and setInterval() gives two completely different results.actually setInterval() hanged by browser several times .what is the basic difference between the two function??

我试图根据我向下滚动页面的程度在 y 方向沿大 div 移动一个小 div。但我发现使用 setTimeout() 和 setInterval() 会给出两个完全不同的结果。实际上是 setInterval( ) 被浏览器挂了好几次。这两个功能的基本区别是什么??

<!DOCTYPE html>
<head>
<title>creat a dynamic div</title>
<style>
#mydiv{
border:2px solid green;
}
</style>
</head>
<body>
<script>
var i=0;
var elem1=document.createElement("div");
var atts1=document.createAttribute("style");

atts1.value="width:200px;height:3200px;border:1px solid black;background-color:orange;";
elem1.setAttributeNode(atts1);
document.body.appendChild(elem1);

var elem2=document.createElement("div");
var atts2=document.createAttribute("style");
var atts22=document.createAttribute("id");
atts22.value="mydiv";
atts2.value="width:200px;height:300px;background-color:red;position:absolute;top:0px;left:300px;";
elem2.setAttributeNode(atts2);
elem2.setAttributeNode(atts22);
document.body.appendChild(elem2);

function moveIt(){
var a=window.pageYOffset;


if(i > (a+30)){

clearTimeout(p);

}else{
elem2.style.top=i+"px";
i=i+1;
}
var p=setTimeout(moveIt,200);
}

window.onscroll=moveIt;

</script>
</body>
<html>

回答by Scott

setTimeoutexecutes the function once on a time out. setIntervalexecutes the function repeatedly on and interval

setTimeout超时执行一次函数。 setInterval在和间隔上重复执行该函数

https://developer.mozilla.org/en-US/docs/Web/API/Window.setTimeout
https://developer.mozilla.org/en-US/docs/Web/API/Window.setInterval

https://developer.mozilla.org/en-US/docs/Web/API/Window.setTimeout
https://developer.mozilla.org/en-US/docs/Web/API/Window.setInterval

回答by Anthony Elliott

setTimeoutwill only execute the function once whereas setIntervalwill execute the function every nseconds (whatever you specify).

setTimeout只会执行一次该函数,而setInterval会每隔n几秒执行一次该函数(无论您指定什么)。