Reputation: 674
I am currently in a situation where I am using setInterval() in order to create buttons which flicker at particular frequencies on screen. Like so: (element refers to the button)
setInterval(function() {
if($(element).css("background-color") === darkColor){ //if colour is dark
$(element).css("background-color", lightColor); //set to light
}else if($(element).css("background-color") === lightColor){ //if colour is light
$(element).css("background-color", darkColor); //set to dark
}
}, frequency); //frequency value is in milliseconds
I lately read on the Internet that requestAnimationFrame() function is generally better for displaying timed on-screen animations. Do you know how requestAnimationFrame() can be used in such a situation or if it is even suitable to use it in such a situation?
Note: It is mandatory that Javascript is used to perform the flicker effect (no CSS)
Thank you
Upvotes: 1
Views: 3378
Reputation: 26878
You use requestAnimationFrame()
by giving it a function reference. If you want to continuously call it with the same function, have the function recursively schedule another requestAnimationFrame()
, it doesn't continuously fire as setInterval()
does, it acts more like setTimeout()
.
If you want to delay the next request, then you aren't really getting a benefit over setInterval
or setTimeout
because you still have to schedule the next animation frame request after an amount of time. requestAnimationFrame()
just says, "Hey browser, next time you go to paint the window, run this function while you're at it."
You're going to run into issues comparing colors like this. You might get an rgb(n, n, n)
in some cases or maybe a hex string in others. I don't know the API specs.
Warning, the examples below will flicker colors very fast
function change() {
if ($("#foo").css("background-color") === "rgb(0, 128, 0)") {
$("#foo").css("background-color", "rgb(128, 0, 0)");
} else {
$("#foo").css("background-color", "green");
}
setTimeout(()=>requestAnimationFrame(change), 500);
}
$("#foo").css("background-color", "red");
requestAnimationFrame(change);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="foo">M</span>
Also, I really would suggest you using CSS animations instead.
#foo {
animation: 500ms flicker infinite steps(1);
}
@keyframes flicker {
0% {
background-color: rgb(256, 0, 0);
}
50% {
background-color: rgb(0, 256, 0);
}
}
<span id="foo">M</span>
Upvotes: 2