Loops
Computers often need to repeat the same thing over and over
• Pretest
var i=1, sum=0;
while (i<5)
{ sum += i++; }
alert(sum);
• Post-test loop
var i=0, sum=0;
do
{ sum += i++;
} while (i<=5);
alert(sum);
• Questions
• Counter controlled
var i=0, sum=0;
for (i=1; i<=5; i++) sum += I;
alert(sum);
– Print "Hello" 100 times
– Count backwards from 100
to 1
– Lets do some examples in
the book
<html><head><title>Move the Mouse</title>
<style>
div {position:absolute; left:0px; top:100px; width:100px; height:100px; }
</style>
<script type="text/javascript">
var position=-95;
var speed = Math.floor(Math.random()*10)+2;
Animation
A Moving Mouse
function next()
{ position+=speed;
if (position>795) position=-95;
document.getElementById("mouse").style.left=position + 'px';
window.setTimeout("next();",10);
}
</script></head>
<body onload="next();">
<div id="mouse">
<img src="mouse.gif" width="100" height=" 100" border="0" alt="mouse">
</div>
</body></html>
Modify the position of the <div> tag and repeatedly call the next()
function every 10 milliseconds using calls to setTimeout()
A Scrolling
Message
<body onload="scrollIt();">
<table border="1" width="90%">
<tr><td id="scroll" width="90%">
</td></tr></table></body>
http://cs.sou.edu/~harveyd/classes/cs210/examples/week9/scroll.htm
<script language="JavaScript">
var middle = 0;
var msg = "This is an example of a scrolling message. ";
function ScrollIt()
{ var text = msg.substring(middle, msg.length) +msg.substring(0,middle);
var td = document.getElementById("scroll");
td.innerHTML = text;
if (++pos > msg.length) pos = 0;
window.setTimeout("ScrollIt()",200); Repeat every fifth of a second
}
</script>
Concept: display from middle to end, and then from front to middle
Review Questions
1.
2.
3.
4.
5.
6.
7.
8.
What are the three kind of loops? How do you determine
which to use?
How do you create an array of strings?
How do you change the text content of a tag?
How do you find the element with attribute "id='scroll'"?
What are three examples where arrays are useful?
How does the setTimeout() function work?
What is a scrolling message? How do you create such a
message using JavaScript and HTML?
How do you use a loop to cause an image to move in a
browser window?
© Copyright 2026 Paperzz