View Full Version : Simple Slide Show: setInterval() problem

n00bosaurus rex
Jul 24th, 2011, 07:02 PM
I realize this is an overly simple question, but I'm rather horrible at javascript. What I'm doing is changing an img src and having it loop through images. I want it to only start looping when I click and than stop if I click again.

It loops through when I click once, but when I click again it starts changing its rate of image switching. Starts off switching at 1000 milliseconds than upon clicking again it switches through two images quickly and than slows again.

var myImage = document.getElementById("mainImage");

var imageArray=["1.jpg","2.jpg","3.jpg","4.jpg" ];

var imageIndex=0;

What I assume is the trouble causing function:

function changeImage(){
myImage.setAttribute("src", imageArray[imageIndex]);
if(imageIndex >= imageArray.length) {

How the trouble function is being called:

var imgSwtch=0;

myImage.onclick= function(){
var intervalHandle = setInterval(changeImage,1000);


Jul 24th, 2011, 07:24 PM
intervalHandle variable is local, defined within onclick function only. Out of this fucntion it is not defined. Make this global.

n00bosaurus rex
Jul 24th, 2011, 08:35 PM
Thanks a lot! Works perfectly now.

Am wondering though, I've been reading articles on scope to refresh my memory, but I'm not sure I understand why the variable should be global in this case. Does the else statement just not recognize the intervalHandle variable? Was thinking it is inside the function so shouldn't it still be able to clear that? Missing something obvious I think.

Jul 24th, 2011, 08:43 PM
Each time when a function begins to execute local variables are created and local variables are destroyed when a function finishes. This is your issue. To keep some state of a function between two or more calls keep it in a global variable. This is usual way.