JSFiddle - React, Tailwind, and code Playground
by baacke
HTML
<button id="start">Start</button>
<br><br>
Timer: <span id="time"></span>
<br>
Question: <span id="wrap">
<span id="question"></span> / 40
<div id="progress"></div>
</span>
<br><br>
"<span id="motivation"></span>"
CSS
body {
font-size: 1.2em;
}
span {
font-weight: bold;
}
#wrap {
display: inline-block;
width: 300px;
border: 1px solid #ccc;
text-align: center;
position: relative;
}
#progress {
height: 100%;
background-color: #AFFFCB;
position: absolute;
top: 0;
left: 0;
z-index: -1;
transition: width 1s linear;
}
#motivation {
font-style: italic;
}
JavaScript
var secondsInMinute = 60,
testTime = 60,
questions = 40,
secondsPerQuestion = (testTime / questions) * secondsInMinute,
testTimeInSeconds = testTime * secondsInMinute,
timeLeft = testTimeInSeconds,
time = document.getElementById('time'),
question = document.getElementById('question'),
progress = document.getElementById('progress'),
motivation = document.getElementById('motivation'),
quotes = ["Great Job!", "You're doing great, Kris", "Keep it up!", "Wow, you're smart!", "Great Pace!", "You're going to pass!", "You're doing fantastic", "Good job!", "Great answer!", "You're almost done!"];
$('#start').click(function(){
startTimer();
});
function startTimer() {
setInterval(function(){
var minutesLeft = parseInt(timeLeft / secondsInMinute),
remainingSeconds = n(timeLeft % secondsInMinute);
timer = minutesLeft + ":" + remainingSeconds;
time.innerHTML = timer;
if (timeLeft > 0) {
timeLeft--;
}
var elapsedTime = testTimeInSeconds - timeLeft,
currentQuestion = Math.ceil(elapsedTime / secondsPerQuestion),
timerWidth = elapsedTime % secondsPerQuestion,
progressPercent = ((secondsPerQuestion - ((currentQuestion * secondsPerQuestion) - elapsedTime)) / secondsPerQuestion) * 100;
question.innerHTML = currentQuestion;
progress.style.width = progressPercent + "%";
var newQuoteIndex = parseInt((Math.random() * 10) - 1);
if (elapsedTime % 5 === 0) {
motivation.innerHTML = quotes[newQuoteIndex];
}
}, 1000);
}
function n(n){
return n > 9 ? "" + n: "0" + n;
//n(9); //Returns "09"
//n(10); //Returns "10"
}