document.addEventListener('DOMContentLoaded', function() { const kickDrumAudio = document.getElementById('kickDrumAudio'); const bpmSelector = document.getElementById('bpmSelector'); const startButton = document.getElementById('startButton'); let timer = null; // Timer to manage the interval of the drum beat function accurateInterval(callback, timeInterval) { let timeout; // Declare timeout here to ensure it can be cleared let expected = Date.now() + timeInterval; function round() { let drift = Date.now() - expected; if (drift > timeInterval) { // Optionally handle significant drift here } callback(); expected += timeInterval; timeout = setTimeout(round, Math.max(0, timeInterval - drift)); } return { start: function() { timeout = setTimeout(round, timeInterval); }, stop: function() { clearTimeout(timeout); // Clear the specific timeout } }; } startButton.addEventListener('click', function() { if (startButton.textContent === "Start") { startButton.textContent = "Stop"; const bpm = parseInt(bpmSelector.value, 10); const intervalDuration = 60000 / bpm; timer = accurateInterval(function() { kickDrumAudio.currentTime = 0; // Reset audio to ensure it starts from the beginning kickDrumAudio.play(); }, intervalDuration); timer.start(); } else { if (timer) { timer.stop(); } kickDrumAudio.pause(); // Ensure the audio is paused kickDrumAudio.currentTime = 0; // Reset the audio position startButton.textContent = "Start"; } }); }); Metro V.1.0 – g21academy.ae
G21 Simple Metronome
>