I have an animation and JS for alternating 2 divs and change their background images (from an array of a few dozens images), sort of interchangeable divs. Everything works just fine, however when the animation runs I can see that my CPU is at 100%. At first I thought it might be due to setInterval, however when I changed the code from alternating the images to just increase a number with each iteration and log it to console - I saw dramatic CPU overload decrease, of about 40-50%. So I understood it might be due to animation.
Here's my HTML code:
<div class="wallpaper wallpaper-1" id="wallpaper-1"></div> <div class="wallpaper wallpaper-2" id="wallpaper-2"></div> CSS:
.wallpaper { width: 100%; height: 100%; position: absolute; opacity: 0; background-repeat: no-repeat; background-position: center; background-size: cover; -webkit-transform: translateZ(0); -webkit-animation-timing-function: linear; } .animate { -webkit-animation-name: fadeInOut; -webkit-animation-duration: 6s; } @-webkit-keyframes fadeInOut { 0% { opacity: 0; -webkit-transform: scale(1); } 16% { opacity: 1; } 90% { opacity: 1; } 100% { opacity: 0; -webkit-transform: scale(1.1); } } And JS that makes it all tick:
Wallpapers.get().then(function(list) { var wp1, wp2, divs = [], path, bgs = [], counterBgs = 0, bgsLength, currentId, doInterval; wp1 = document.getElementById('wallpaper-1'); wp2 = document.getElementById('wallpaper-2'); divs = [ wp1, wp2 ]; path = 'assets/img/wallpapers/'; bgs = list.data; bgsLength = bgs.length; //Preload images for(var i = 0; i < bgsLength-1; i++) { var wp = new Image(); wp.src = path+list.data[i]; } function manageBg() { setInterval(function(){ doInterval(); }, 4000); } doInterval = function doInterval() { currentId = counterBgs % bgsLength; if (counterBgs % 2 === 0) { wp1.style.backgroundImage = "url(" + path + bgs[currentId] + ")"; wp1.classList.add('animate'); wp1.style.zIndex = 1; wp2.style.zIndex = 0; setTimeout(function() { wp1.classList.remove('animate'); }, 5950); } else { wp2.style.backgroundImage = "url(" + path + bgs[currentId] + ")"; wp2.classList.add('animate'); wp1.style.zIndex = 0; wp2.style.zIndex = 1; setTimeout(function() { wp2.classList.remove('animate'); }, 5950); } counterBgs++; }; doInterval(); manageBg(); }); Any ideas how to reduce the CPU overload?
transform: translateZ(0);. It somewhat helped, the load was reduced by 3-4% in average. Without it the CPU was constantly on 100%.animationendevent to trigger the next image and never have to bother with z-index at all-moz-border-radius: 3px; border-radius: 2px;-> W3 standard is used,border-radius: 2px; -moz-border-radius: 3px;-> Mozilla prefix is used. Also, for experimental features some browsers still rely on their vendor-prefixed implementation. This differs per property.