How To Prevent Auto Run

I’m just starting to learn js and have found a useful script but it runs when the page loads. How can I change it run from a button onclick. It is only then that I can begin to play with it and change things while learning. This is the code:

<div>
   <p id="output">Result</p>
</div>

    const output = document.querySelector("#output");
    const display = s => output.innerText = s;
    const names = [
      "Charley",
      "Dianne",
      "Ellen",
      "Ethel",
      "Venus"
    ];
    const delayLoop = (fn, delay) => {
      return (name, i) => {
        setTimeout(() => {
          display(name);
        }, i * 1000);
      }
    };
    names.forEach(delayLoop(display, 1000));

I want to call it with

Hi @Edwin_Devey - welcome to the forums :slight_smile:

What you can do is have a button with an event listener function that reacts to the click event. This article goes into more detail here: https://www.kirupa.com/html5/mouse_events_in_javascript.htm

For example, you can do something similar:

let button = document.querySelector("#myButton");
button.addEventListener("click", doSomething, false);

function doSomething(e) {
    const output = document.querySelector("#output");
    const display = s => output.innerText = s;
    const names = [
      "Charley",
      "Dianne",
      "Ellen",
      "Ethel",
      "Venus"
    ];
    const delayLoop = (fn, delay) => {
      return (name, i) => {
        setTimeout(() => {
          display(name);
        }, i * 1000);
      }
    };
    names.forEach(delayLoop(display, 1000));
}

You just need to have a button in your HTML with the id value of myButton.

Thank you for a very prompt reply. Can’t wait to read the article and have a go again.

Let us know how it goes! :grinning: