May 27, 2013

JavaScript: Throttle requestAnimationFrame to maintain 30fps

One problem with using requestAnimationFrame is that rendering will take place as quickly as the computer can process the per-frame calculations and screen redraw. If you only want to run at 30fps, your computer might be running a lot faster than you want. To work around this problem, simply check the elapsed time before running the next frame update. Check out the example:
var frameLength = 33; // this is ~1/30th of a second, in milliseconds (1000/30)
var lastFrame = 0;

var render = function() {
  if( - lastFrame > frameLength) {
    lastFrame =

    // run your 30fps code here...
You'll notice that I'm using, which requires a polyfill for old versions of IE. requestAnimationFrame also requires a polyfill for some browsers. Another solution is to use time-based calculations, but that's not always easy to implement.

May 25, 2013

Bookmarklet: Scrub through a Vine video

I was watching a friend's Vine video on the web, and I got the idea that it would be cool to control the playback of the video. I wrote this little bookmarklet to scrub through the video as you move your mouse over it. Here's the original JavaScript:
// grab video element and pause it
var vid = document.getElementById('post_html5_api'); 
// get x offset of video
var vidX = 0; 
var el = vid;
while (el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
  vidX += el.offsetLeft;
  el = el.offsetParent;
// scrub the video based on mouse x
var vidTime = vid.seekable.end(0); 
vid.addEventListener('mousemove', function(e) {
  var x = e.clientX - vidX;
  var percent = x / vid.offsetWidth;
  vid.currentTime = percent * vidTime;
}, false);
And the bookmarklet (Vine Scrubber):