Adrian MacNair wrote on 26 apr 2005 in comp.lang.javascript
:
Hi, it's been about 5 years since I did JavaScript so I was wondering
if I could get some help with a little problem. I wrote a script from
memory (5 years!!) and the only problem I have is clearing the
timeout. Please advise:
<script language="JavaScript">
That was 5 year ago
<script type="text/JavaScript">
var myvar = 0
var myTimeout;
// Initiate is called onmouseover
This is a bad idea, becaus succesive onmouseovers will
interfere with the setTimout call.
function initiate() {
The name wrongly suggests it is only called once
images = new Array
better use var here for appearance sake
var myImages = new Array();
images[0] = "11210.jpg"
images[1] = "11211.jpg"
images[2] = "11212.jpg"
Take these out of the function,
you dont want to define then every half second again
var image = images[myvar]
don't use possibly reserved names like "image",
you don't need this variable at all anyway
document.data.src = image
// If the images haven't reached the end keep going
if (myvar<3) {
myvar++
setTimeout("initiate()",500);
This you need:
myTimeout=setTimeout("initiate()",500);
// otherwise start over
} else {
myvar=0
setTimeout("initiate()",500);
}
}
// Stop the timeouts!
function stop() {
// This doesn't stop the timeouts
clearTimeout()
clearTimeout(myTimeout)
}
</script>
================================
so:
<script type="text/JavaScript">
// initation
var myvar = 0;
var myTimeout;
var running = false;
var myImages = new Array();
myImages[0] = "11210.jpg";
myImages[1] = "11211.jpg";
myImages[2] = "11212.jpg";
function start() { // onmouseover or button onclick?
if (!running) {
running=true;
nextimg();
}
};
function nextimg() {
document.getElementById('imgId').src = myImages[myvar];
myvar++;
if (myvar>2) myvar=0;
myTimeout = setTimeout("nextimg()",500);
};
function stop() { // other button onclick?
if (running) {
running=false;
clearTimeout(myTimeout);
};
};
</script>
not tested!!!
--
Evertjan.
The Netherlands.
(Replace all crosses with dots in my emailaddress)