JSFiddle - React, Tailwind, and code Playground

by mohayonao

HTML

<button id="test">test</button>

JavaScript

var AudioContext = window.AudioContext || window.webkitAudioContext;

var timerId = 0;
var GCGuard = [];
var audioContext = new AudioContext();

function bang() {
    var t0 = audioContext.currentTime;
    var t1 = t0 + 1;
    var t2 = t1 + 1;
    var osc = audioContext.createOscillator();
    var amp = audioContext.createGain();
    
    osc.frequency.value = 440;
    osc.start(t0);
    osc.stop(t2);
    osc.connect(amp);
    
    amp.gain.setValueAtTime(0.5, t0);
    amp.gain.setValueAtTime(0.5, t1);
    amp.gain.linearRampToValueAtTime(0.0, t2);
    amp.connect(audioContext.destination);
    
    osc.onended = function() {
        var index = GCGuard.indexOf(osc);
        if (index !== -1) {
            GCGuard.splice(index, 1);
        }
    };
    GCGuard.push(osc);
}

function start() {
    timerId = setInterval(bang, 1000);
}

function stop() {
    clearInterval(timerId);
    timerId = 0;
}

document.getElementById("test").onclick = function() {
  if (timerId === 0) {
      start();
  } else {
      stop();
  }
};