html – setTimeout function in javascript is being called but not setting timeout-ThrowExceptions

Exception or error:
var r = 0;
var g = 0;
var b = 225;

function gradient() {
    b = b - 10;
}

while (b> 6){
    setTimeout(gradient(),1000);
}


ctx.beginPath();
ctx.fillStyle= 'rgb('+r+', '+g+', '+b+')'
ctx.rect(0,0,1200,590,2*Math.PI)
ctx.stroke()
ctx.fill();
ctx.closePath();

I know the while loop and function are working because the variable b is decreased and the color of the canvas image is changed. But there is no delay and it happens instantly. I have tried with the setInterval function as well but I can’t get it to work.

How to solve:

Try This:

 var r = 0;
 var g = 0;
 var b = 225;

 function gradient() {

   if(b > 6){
      console.log(b);
      b = b - 10;
      setTimeout(gradient,1000);
   }

 }

 gradient();

 ctx.beginPath();
 ctx.fillStyle= 'rgb('+r+', '+g+', '+b+')'
 ctx.rect(0,0,1200,590,2*Math.PI)
 ctx.stroke()
 ctx.fill();
 ctx.closePath();

Leave a Reply

Your email address will not be published. Required fields are marked *