Search code examples
javascripttimeoutsetinterval

How to change the value of Variable in setInterval


the Value of time will change just one time in the method setInterval i would like to change it with the value of checkLevel

var time = checkLevel();

//die Methode wird nach msecLevel aufgerufen

    setInterval(function (event) {
       
        time = checkLevel();
        if (!isLoser) {
            //Leere die Fläche
            ctx.clearRect(0, 0, canvasWidth, canvasHeight);
            //Neu durchführen
            randomX = getRandomPosition(canvasWidth - fishSize);
            randomY = getRandomPosition(canvasHeight - fishSize);
            var randomFish = Math.floor(Math.random() * 11) + 1;
            fish.src = 'images/fish' + randomFish + '.png';

        }
    }, time);

Solution

  • You can create a recursive function that changes the interval, then simply call the interval once to start it, then the function will just change the interval every call.

    var _timer;
    
        function showFish(){
               if (!isLoser) {
                    //Leere die Fläche
                    ctx.clearRect(0, 0, canvasWidth, canvasHeight);
                    //Neu durchführen
                    randomX = getRandomPosition(canvasWidth - fishSize);
                    randomY = getRandomPosition(canvasHeight - fishSize);
                    var randomFish = Math.floor(Math.random() * 11) + 1;
                    fish.src = 'images/fish' + randomFish + '.png';
               }
    
             _timer = setTimeout(showFish,  checkLevel());
        }
        
         _timer = setTimeout(showFish,  checkLevel());