Cut And Paste Code For Timers


Click here to go back to our lessons page.


Simple timer using "setInterval" and "innerHTML" to print results:

<html>
<body>
<p id="demo"></p><script>
var d = 0;
var myVar = setInterval(myTimer, 1);
function myTimer() {
d++;
document.getElementById("demo").innerHTML = d;
}
</script>
</body>
</html>


Big Timer Using "canvas" and text drawing tools to print results:

<html>
<body>
<canvas id="myCanvas" width="335" height="118" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.font = "35px Arial";
ctx.fillStyle="black";
ctx.fillRect(0,0,335,118);
ctx.clearRect(60, 10, 210, 40);
ctx.fillText("Big Time...",90,40);
var d = 0;
//The nuber following myTimer below determines the delay.  1000 = 1 second
var myVar = setInterval(myTimer, 100);
function myTimer() {
d++;
ctx.clearRect(20, 70,297, 36);
ctx.fillText(d,40,100);
}
</script>
</body>
</html>


Big Timer Using "canvas" and text drawing tools to print results + color gradients just for fun...:

<html>
<body>
<canvas id="myCanvas" width="335" height="160" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.font = "35px Arial";
var gradient = ctx.createLinearGradient(0, 0, c.width, 0);
gradient.addColorStop("0", "magenta");
gradient.addColorStop("0.5", "blue");
gradient.addColorStop("1.0", "red");
// Fill with gradient
ctx.fillStyle = gradient;
ctx.fillRect(0,0,335,160);
ctx.clearRect(60, 10, 210, 40);
ctx.fillText("Big Time...",90,40);
var d = 0;
//The nuber following myTimer below determines the delay.  1000 = 1 second
var myVar = setInterval(myTimer, 1);
function myTimer() {
d++;
ctx.clearRect(20, 70,297, 50);
ctx.fillText(d,40,108);
}
</script>
</body>
</html>