Created
January 4, 2014 00:02
-
-
Save palmerj3/8249237 to your computer and use it in GitHub Desktop.
A simple example of a timer using requestAnimationFrame
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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