...

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



n00bosaurus rex
07-24-2011, 06: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]);
imageIndex++;
if(imageIndex >= imageArray.length) {
imageIndex=0;
}
}


How the trouble function is being called:


var imgSwtch=0;

myImage.onclick= function(){
if(imgSwtch==0){
var intervalHandle = setInterval(changeImage,1000);
imgSwtch=1;
console.log("start");
}
else{
clearInterval(intervalHandle);
imgSwtch=0;
console.log("stop");
}

};

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

n00bosaurus rex
07-24-2011, 07: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.

siberia-man
07-24-2011, 07: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.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum