Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
165
rated 0 times [  170] [ 5]  / answers: 1 / hits: 17441  / 10 Years ago, wed, april 2, 2014, 12:00:00

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>

More From » javascript

 Answers
58

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


[#71645] Tuesday, April 1, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kiyam

Total Points: 448
Total Questions: 96
Total Answers: 92

Location: Philippines
Member since Sat, Jul 11, 2020
4 Years ago
;