One tab open at one time for accordion

I have this accordion opening all tabs at same time but i want it to open one tab at one time and when you click on other tab it closes the previous tab.
I tried to play with the javascript but only I can get is the tab not opening completely.

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight) {
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    }
  });
}
<button class="accordion">Section 1</button>
<div class="panel">
  <p>CONTENT 1</p>
</div>

<button class="accordion">Section 2</button>
<div class="panel">
  <p>CONTENT 2</p>
</div>

<button class="accordion">Section 3</button>
<div class="panel">
  <p>CONTENT 3.</p>
</div>