Skip to content

Instantly share code, notes, and snippets.

@palmerj3
Created January 4, 2014 00:02
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save palmerj3/8249237 to your computer and use it in GitHub Desktop.
Save palmerj3/8249237 to your computer and use it in GitHub Desktop.
A simple example of a timer using requestAnimationFrame
<html>
<head>
</head>
<body>
<h1 id="display"></h1>
<script type="text/javascript">
(function() {
// Source: http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
// shim layer with setTimeout fallback
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
var lastTime = (new Date()).getTime();
var displayNode = document.getElementById('display');
var numSeconds = 0;
(function timer() {
requestAnimFrame(timer);
var currentTime = (new Date()).getTime();
if (currentTime - lastTime >= 1000) {
console.log("Last Time: " + lastTime);
console.log("Current Time: " + currentTime);
lastTime = currentTime;
numSeconds++;
displayNode.innerText = numSeconds;
}
}());
}());
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment