Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I decrease the my setInterval as score goes up?

I am making a little game similar to tetris. I need the blocks to fall faster as the players score goes up I currently have this code:

setInterval(function(){
    if(gameOn == 1){
        gravity();
    }
},1000);

This calls my gravity function and which makes the blocks drop down and does all the collision detection etc.

var time = 1000 - score;

setInterval(function(){
        if(gameOn == 1){
            hideStuff('hover');
            gravity();
            time = 1000 - score;
        }
    },time);

I thought something like this might work, but it doesn't seem to. Any ideas? Thanks

like image 366
Stewart Webb Avatar asked Nov 23 '25 07:11

Stewart Webb


2 Answers

You could do a setTimeout loop. That way, every call to setTimeout will reflect any changes done to the value of time

var time = 1000;

(function foo(){

  if(gameOn == 1){
    hideStuff('hover');
    gravity();
    time = 1000 - score;
  }

  setTimeout(foo,time);

}());
like image 182
Joseph Avatar answered Nov 24 '25 20:11

Joseph


You'll need to clear the interval and re-start it whenever you want to change the delay:

window.icount = setInterval(function(){
    if(gameOn == 1){
        gravity();
    }
},1000);


var time = 1000 - score;

clearInterval(window.icount);
window.icount = setInterval(function(){
        if(gameOn == 1){
            hideStuff('hover');
            gravity();
            time = 1000 - score;
        }
    },time);
like image 35
Blazemonger Avatar answered Nov 24 '25 21:11

Blazemonger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!