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?