setTimeout()和setInterval()之间的区别

时间:2014-04-02 23:55:48

标签: javascript

我试图根据我向下滚动页面的方向在y方向沿着一个大div移动一个小div。但是我发现使用setTimeout()和setInterval()给出两个完全不同的results.actually 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>

2 个答案:

答案 0 :(得分:9)

setTimeout在超时时执行一次该功能。 setInterval重复执行函数和interval

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

答案 1 :(得分:3)

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

相关问题