stacked on setinterval

Posted on
  • I try to make a loop with a dynamic intervaltime.
    I don't know how to fix this.
    Do someone have a suggestion for me?

    var c = 1;
    var time = 15;
    function flash(time){
      on = !on;
      digitalWrite(A0, on);
      
      c++;
      if(c >= 20){
        digitalWrite(LED1, 1);
      } 
      if(c >= 40){
        digitalWrite(LED2, 1);
      }
      if(c >= 60){
        digitalWrite(LED3, 1);
      }
      if(c >= 80){
        c = 0;
        digitalWrite([LED1, LED2, LED3],0);
        time += 25;
        return time;
        
      }
    }
    
    setInterval(flash,time);
    

    Thanks!

  • The problem is that when you change the variable a interval uses the interval doesn't actually change, to change it you have to assign the interval to a variable and then use the function changeInterval. So to fix your code you could either use changeInterval or use could make the function call itself with timeouts instead of intervals (Timeouts call once after the time then get deleted).
    With Timeouts:

    var c = 1;
    var time = 15;
    
    function flash(){
      on = !on;
      digitalWrite(A0, on);
      
      c++;
      if(c >= 20){
        digitalWrite(LED1, 1);
      } 
      if(c >= 40){
        digitalWrite(LED2, 1);
      }
      if(c >= 60){
        digitalWrite(LED3, 1);
      }
      if(c >= 80){
        c = 0;
        digitalWrite([LED1, LED2, LED3],0);
        time += 25;
      }
      setTimeout(flash,time);
    }
    
    flash();
    

    Or with changeInterval:

    var c = 1;
    var time = 15;
    
    function flash(){
      on = !on;
      digitalWrite(A0, on);
      
      c++;
      if(c >= 20){
        digitalWrite(LED1, 1);
      } 
      if(c >= 40){
        digitalWrite(LED2, 1);
      }
      if(c >= 60){
        digitalWrite(LED3, 1);
      }
      if(c >= 80){
        c = 0;
        digitalWrite([LED1, LED2, LED3],0);
        time += 25;
        changeInterval(loop, time);
      }
    }
    var loop = setInterval(flash,time);
    
  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

stacked on setinterval

Posted by Avatar for Bert-Holland @Bert-Holland

Actions