Reputation: 35
I have written the function below which is supposed to run itself every 20ms until a colour fade has completed, but the fade happens instantly - why?
function saveColour()
{
if(x<=speedms/frameratems)
{
currentRed=Math.floor((x*deltaRed)+oldRGB[0]);
currentGreen=Math.floor((x*deltaGreen)+oldRGB[1]);
currentBlue=Math.floor((x*deltaBlue)+oldRGB[2]);
document.getElementById(id).style.backgroundColor="rgb("+currentRed+", "+currentGreen+", "+currentBlue+")";
//window.alert("rgb("+currentRed+", "+currentGreen+", "+currentBlue+")");
x++;
setTimeout(saveColour(),frameratems);
}
}
The setTimeout seems to run instantly, no matter what I set frameratems to and I'm not sure why.
Thank you!
Upvotes: 2
Views: 87
Reputation: 9583
setTimeout expects a function reference as the first parameter
by calling it with setTimeout(saveColour(),frameratems);
you're passing it the return value of saveColour
that would be ok if saveColour
returned a function.
use
setTimeout(saveColour,frameratems);
instead
Upvotes: 4