Reputation: 8531
My website has a simple JS animation. It animates a bunch of photos contained in #frame1
, and loops then around the screen indefinitely. #frame1
is actually a 1920x1080 area, which is constantly a rotating photo display.
The memory footprint of this in Chrome keeps growing. It grows pretty quickly at this speed (50
), and slower at 100. This seems to be because of the large amount of pixels being moved around. Is there any way I can improve the memory performance of this app, without reducing the speed of the interval?
function start_scroll() {
var elem1 = document.getElementById("frame1");
var pos1 = 0; // Starting position of box1.
var id = setInterval(frame, 50); // Set speed here.
function frame() {
if (pos1 == frameheight * -1) { // If it just disappeared, move it to the bottom and populate it with the next series of pics.
pos1 = frameheight;
populate(1); // Populate the first frame with the next set of pics.
} else { // Otherwise, keep on moving up.
pos1--;
elem1.style.top = pos1 + 'px';
}
}
}
Upvotes: 0
Views: 45
Reputation:
Replace setInterval()
with requestAnimationFrame()
. This will sync the animation with the monitor update in an efficient matter.
function start_scroll() {
var elem1 = document.getElementById("frame1");
var pos1 = 0;
//var id = setInterval(frame, 50); // don't use setInterval
requestAnimationFrame(frame); // start once, using rAF
function frame() {
if (pos1 == frameheight * -1) {
pos1 = frameheight;
populate(1);the next set of pics.
} else {
pos1--;
elem1.style.top = pos1 + 'px';
}
requestAnimationFrame(frame); // loop using rAF
}
}
The animation can be stopped using cancelAnimationFrame(timeRef)
or a flag.
var timeRef;
Inside the loop:
timeRef = requestAnimationFrame(frame); // loop using rAF
The typical frame-rate would be 60 frames per second. On some high-end monitors perhaps more. You can use the provided time-stamp to regulate this.
function loop(timestamp) {
// compare time here
requestAnimationFrame(loop); // loop
}
requestAnimationFrame(loop); // start
Upvotes: 2
Reputation: 5534
You cold use requestAnimationFrame
more or less like so:
function start_scroll() {
var elem1 = document.getElementById("frame1");
var pos1 = 0; // Starting position of box1.
var id = setTimeout(frame, 50); // Set speed here.
function frame() {
requestAnimationFrame(frame);
if (pos1 == frameheight * -1) { // If it just disappeared, move it to the bottom and populate it with the next series of pics.
pos1 = frameheight;
populate(1); // Populate the first frame with the next set of pics.
} else { // Otherwise, keep on moving up.
pos1--;
elem1.style.top = pos1 + 'px';
}
}
}
Of course I haven't been able to test that but you could read a comprehensive tut here: http://creativejs.com/resources/requestanimationframe/
Upvotes: 0