Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the speed of setInterval in real time

Tags:

javascript

I would like to know how to change the speed of setInterval in real time e.g:

if (score < 10)
    repeater = setInterval(function() {
        spawnEnemy();
    }, 1000);
if (score => 10)
    repeater = setInterval(function() {
        spawnEnemy();
    }, 500);

I know this method doesn't work, but is there a way that I can achieve this some other way?

like image 556
TeaAnyOne Avatar asked Dec 25 '22 23:12

TeaAnyOne


2 Answers

jsFiddle Demo

There is no way to change the interval speed itself once running. The only way to do it is to have a variable for the speed, and then clear the interval and start a new one with the new speed.

var speed = 500;
var changeSpeed = speed;
repeater = setInterval(repeaterFn, speed);
function repeaterFn(){
    spawnEnemy();
    if( changeSpeed != speed ){
     clearInterval(repeater);
     speed = changeSpeed;
     repeater = setInterval(repeaterFn, speed);
    }
}
function changeRepeater(){
 changeSpeed = 700;
}
like image 55
Travis J Avatar answered Dec 27 '22 13:12

Travis J


Another way would be to just use setTimeout rather than setInterval. Do the check every time so you can keep your speed logic in a seperate function.

var game_over = false;
var score = 0;
function getSpeedFromScore(score)
{
    if (score > 20) {
        game_over = true;
    }

    if (score < 10) {
        return 1000;
    } else {
        return 500;
    }
}

function spawnEnemyThenWait() {
    if (!game_over) {
        spawnEnemy();

        var speed = getSpeedFromScore(score);
        setTimeout(spawnEnemyThenWait, speed);
    }
}

JS Fiddle http://jsfiddle.net/bq926xz6/

like image 21
Phil Avatar answered Dec 27 '22 11:12

Phil