How To Stop a Function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Postdog
    New Member
    • Jan 2012
    • 1

    How To Stop a Function

    Code:
    window.onload = initLinks;
    
    function initLinks() {
    	document.getElementById("rotateBack").onclick = rotateBack;
    	document.getElementById("rotate").onclick = rotateFor;
    }
    
    var thisAd = 0;
    
    var adImages = new Array("catImages/1.png","catImages/2.png","catImages/3.png","shoeImages/4.png","catImages/5.png","catImages/6.png","catImages/7.png","catImages/8.png","catImages/9.png","catImages/10.png");
    
    function rotateFor() {
    	thisAd++;
    	if (thisAd == adImages.length) {
    		thisAd = 0;
    	}
    	document.getElementById("adBanner").src = adImages[thisAd];
    	setTimeout(rotateFor, 500);
    }
    
    function rotateBack() {
    	if (thisAd == 0) {
    		thisAd = adImages.length;
    	}
    	thisAd--;
    	document.getElementById("adBanner").src = adImages[thisAd];
    	setTimeout(rotateBack, 500);
    }
    Hi,

    I'm a beginner and working through a JavaScript tutorial guide, while trying to develop a small project at the same time. A part I'm stuck on involves an animation that runs through a group of images and is triggered by a "rotateFor" button and another button that reverses the animation "rotateBack ".

    I've got each button to work individually in there respective directions, however when I press the second of either two buttons it obviously still remembers the previous function and just jumps back and forth.

    I can't figure out how to cancel the previous function, I realise that it involves implementing something like rotateBack = null; into "rotateFor" function (for example) but I don't understand enough to implement this correctly.

    Thanks in advance for any help,

    Phil
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    Use the clearTimeout function to cancel it.

    Comment

    Working...