Skip to content

Instantly share code, notes, and snippets.

@joshteng
Created March 5, 2017 09:12
Show Gist options
  • Save joshteng/e6053325a5113c61fa80100523daa703 to your computer and use it in GitHub Desktop.
Save joshteng/e6053325a5113c61fa80100523daa703 to your computer and use it in GitHub Desktop.
Simple HTML Timer to Demonstrate Javascript on a Browser
<html>
<head>
<style>
p#secondsLeft {
padding-top: 100px;
text-align: center;
font-size: 50px;
}
p.secondsLeftText {
text-align: center;
}
</style>
</head>
<body id='body'>
<h1>Josh's Timer</h1>
<p id="secondsLeft">?</p>
<p class="secondsLeftText">Seconds Left</p>
<input type='text' name='seconds' id='secondsInput'>
<input type='submit' onclick="startTimer();">
<script>
//this function is called when secondsLeft reaches 0 at line #51
function changeBodyColor(){
var colors = ['red', 'orange', 'yellow', 'green', 'blue', 'violet', 'purple']
var bodyElement = document.getElementById('body')
var colorIndex = 0
var bodyColorLoop = setInterval(function(){
bodyElement.style.backgroundColor = colors[colorIndex]
colorIndex = colorIndex + 1
if (colorIndex == 6) {
clearInterval(bodyColorLoop);
}
}, 500);
}
//This function is called when the submit button is pressed (see line #20)
function startTimer() {
var secondsLeftElement = document.getElementById('secondsLeft')
var secondsLeft = document.getElementById('secondsInput').value
var timerLoop = setInterval(function(){
secondsLeftElement.innerHTML = secondsLeft;
secondsLeft = secondsLeft - 1
if (secondsLeft == -1) {
changeBodyColor();
clearInterval(timerLoop);
}
}, 1000);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment