-3

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

<!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>
AL-zami
  • 8,902
  • 15
  • 71
  • 130
  • 1
    Of course they give completely different results. They're completely different functions. A quick look at documentation, a quick search, or a quick test would make clear the difference. – cookie monster Apr 02 '14 at 23:59

2 Answers2

9

setTimeout executes the function once on a time out. setInterval executes the function repeatedly on and interval

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

Scott
  • 1,648
  • 13
  • 21
  • i wrote setTimeout/setInterval inside the function ,so it should keep executing as at the end of the function setTimeout/setInterval should be called again and again,shouldn't it? – AL-zami Apr 03 '14 at 00:03
  • well one thing when you call `var p=setTimeout(moveIt,200);` you are assigning the timer to a new p. So your call to `clearTimeout(p);` is irrelevant. – Scott Apr 03 '14 at 00:06
  • What you have works for me. I think for what you are trying to do you have done it correctly for using setTimeout. If you wanted to call setInterval you need move *var p* out of the function and make sure that you call clearTimeout(p) before you call another setInterval. If you overwrite the reference of p for a setInterval it will just execute forever. – Scott Apr 03 '14 at 00:20
3

setTimeout will only execute the function once whereas setInterval will execute the function every n seconds (whatever you specify).

Anthony Elliott
  • 2,941
  • 5
  • 29
  • 42