I’m a very new javascript user and I’m working on recreating something for my website, in which I’d like it to have have a flash/glow effect every few seconds, with the flash only appearing for a certain amount of time.
here’s what I tried:
let glow = true;
function flash() {
glow = !glow;
if(glow) {
document.querySelector("#logo").style.textShadow = "-2px -2px 0.1em #fff, -2px -2px 0.1em #fff, 2px 2px 0.1em #fff, -2px -2px 0.3em #fff, 2px 2px 0.5em #fff";
}
else{
document.querySelector("#logo").style.textShadow = "0 0 0";
}
}
(function loop() {
var rand = Math.round(Math.random() * (7000 - 4000)) + 4000; // supposed to be how often the flashes occur, from 7s to 4s
var glow = setInterval(flash, 700); // supposed to be max time the flash can stay on screen
setTimeout(function() {
flash();
loop();
}, rand);
}());
and I left comments describing more in detail what I was going for. any help is appreciated, I just started javascript yesterday and mainly wrote that receiving help from other sources, so sorry if it’s hard to read!
2
Answers
You are writing a lot for this. Just use something like the below example:
You keep creating setIntervals without ever getting rid of them so the flash keeps showing, and showing and showing (and it gets more and more as time goes on, if you left it long enough the system may run out of resources!).
If you do want the flash to happen more than once in that random time interval then save the setInterval and delete it before starting another.
However, I understand you want a .7s flash once each time, so use setTimeout instead as this will happen just the once.
Notes:
I made the body background blue simply as a way of seeing the white flash.
There are ways in JS and CSS which would make things a bit simpler. For example using CSS animation for the timing of the flash but I appreciate you are just starting out and practising timeouts etc.
Also nowadays you will find var in JS used less frequently. It’s worth learning about
const
andlet
as they help get the scope of variables more tightly defined and stop you altering things which are really constants.