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); } }
Next, you can pass the milliseconds parameter, which will be the amount of time JavaScript will wait before executing the code. If you omit the second parameter, then setTimeout() will immediately execute the passed function without waiting at all.
setTimeout allows us to run a function once after the interval of time. setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.
setTimeout() is an asynchronous function, meaning that the timer function will not pause execution of other functions in the functions stack. In other words, you cannot use setTimeout() to create a "pause" before the next function in the function stack fires.
The setInterval method has the same syntax as setTimeout : let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...) All arguments have the same meaning. But unlike setTimeout it runs the function not only once, but regularly after the given interval of time.
You need to get rid of the parentheses on doFade()
.
The parentheses invoke the function instantly.
Just use this in stead: doFade
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With