tap-bpm
by Nic Fontaine
HTML
<div id='tap'></div>
<span>tap vals: </span><span id='timeout'></span><br>
<span>average: </span><span id='avg'></span>
CSS
#tap {
height: 50px;
width: 50px;
cursor: pointer;
background: teal;
}
JavaScript
const domTimeout = document.getElementById('timeout')
const tap = document.getElementById('tap')
const avg = document.getElementById('avg')
var firstFlag = false
var timeoutArray = []
var timeoutInc = 0
var tapTimeout
tap.addEventListener('click', function() {
// don't add on first click. will be 0
if (firstFlag) {
clearInterval(tapTimeout)
timeoutArray.push(Math.round(6000/timeoutInc))
timeoutInc = 0
// display val
domTimeout.innerHTML = timeoutArray
// limit array length to keep bpm input fresh
if (timeoutArray.length > 4) {
timeoutArray = timeoutArray.slice(1)
}
// display avg
avg.innerHTML = getAvg()
// enable pushing after first click
} else {
firstFlag = true
}
// counting interval for bpm
tapTimeout = setInterval(function() {
timeoutInc++
// display val
//domTimeout.innerHTML = timeoutInc
if (timeoutInc > 600) {
clearInterval(tapTimeout)
domTimeout.innerHTML = '<i>(too long, clear array)</i>'
}
},10)
})
// average array indices
function getAvg() {
var sum = 0
for (var i=0; i<timeoutArray.length; i++) {
sum+= timeoutArray[i]
}
return Math.round(sum/timeoutArray.length)
}