简体   繁体   中英

Using requestAnimationFrame() as setInterval() Javascript

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

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM