Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
195
rated 0 times [  196] [ 1]  / answers: 1 / hits: 28465  / 14 Years ago, mon, november 8, 2010, 12:00:00

This is my first real dive into JavaScript. Sure I've used it before, but I've never really written anything from scratch.



Anyway, I'm having a very strange problem that I hope someone can figure out for me.



I'm trying to make the text from a div fade from black to white. Simple, yeah?



The following code works. It will change the color to white, however, the setTimeout time of 500ms is being ignored.



If you use Chrome and look at the JS console, you'll easily see that the doFade() method is being called almost instantaneously, not every 500 milliseconds.



Can anyone explain this?



var started = false;
var newColor;
var div;
var hex = 0;

function fadestart(){
if (typeof fadestart.storedColor == 'undefined') {
div = document.getElementById('test');
fadestart.storedColor = div.style.color;
}
if(!started){
console.log('fadestart');
newColor = fadestart.storedColor;
started = true;
setTimeout(doFade(), 500);
}
}

function fadestop(){
console.log('fadestop');
div.style.color = fadestart.storedColor;
started = false;
hex = 0;
}

function doFade(){
if(hex<=238){
console.log(hex);
hex+=17;
div.style.color=rgb(+hex+,+hex+,+hex+);
setTimeout(doFade(), 500);
}
}

More From » settimeout

 Answers
37

You need to get rid of the parentheses on doFade().



The parentheses invoke the function instantly.



Just use this in stead: doFade


[#95044] Thursday, November 4, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zoey

Total Points: 120
Total Questions: 103
Total Answers: 105

Location: Marshall Islands
Member since Mon, May 31, 2021
3 Years ago
;