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");
}
};
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");
}
};