Issues with resetting an interval

70 views Asked by At

I have two elements. When I click the left element I want to change the right element into another element. If the left element is not clicked again the right element changes back to its original state. I've been able to make that happen, but I want to be able to click on that element again and have the interval I set restart. I feel like I'm close.

         var changeImage = function(){
            if(imageClicked == true){

            var Img = document.getElementById('Img');
            Img.setAttribute('src', "./images/img2.jpg");

           imageTimeout = setTimeout(function(){
           var Image = document.getElementById('Image');
            Image.setAttribute('src', './images/image.jpg');
         }, 3000)


         imageClicked = false;
         return imageTimeout;

     } else {
        imageClicked = true;
        resetTimer();
       }

    }

     var resetTimer = function(){
         clearTimeout(imageTimeout);
         window.setTimeout(imageTimeout, 3000);

   }

    random_image.addEventListener("click", changeImage, false);
2

There are 2 answers

0
yvesmancera On

In order to clear a timeout, you need to call the clearTimeout function with the reference to the object that was returned by window.setTimeout. So you need to change your code to:

var resetTimer = function() {
    clearTimeout(timeoutId);
    createjs.Sound.stop(playSoundD);
    timeoutId = window.setTimeout(imagetimeout, 3000);
    console.log("I've been reset");
}
0
Tomer Almog On

The problem is that you are calling setTimeout(function ,delay) without a callback function. The issue is in this line in the else block:

window.setTimeout(imageTimeout, 3000);

where imageTimeout is not a function, but the id of the timeout.

You need to create a separate function (let's call it timeoutFunction for example) with the timeout code and call it every time you invoke setTimeout.

After you create that function, and call it in the if block as well, change that line to:

imageTimeout = window.setTimeout(timeoutFunction, 3000);

from your code:

function timeoutFunction(){
    var flowerImage = document.getElementById('flowerP');
    flowerImage.setAttribute('src', './images/flowers.jpg');
}

by the way, you can define that flowerImage variable outside that function once instead of searching the DOM every time.