How to add text "Please wait a while..." on clicking the button in JavaScript function

Viewed 1445

I had created some function calls using JavaScript and made it delay 7 seconds now I want that when a user clicks the button, a "please wait..." text(not in the button text) appears as soon as the delay time starts.

"Please wait" text should appear as headline tag(h3 or h4 tag)

Any help/suggestion, please...

function yes() {
  var button = document.getElementById('test');
  var name = document.getElementById('name');
  var age = document.getElementById('age');
  var location = document.getElementById('location');
  console.log("clicked on Test-Button");
  var str = 'Hello! <p> My name is Ashish</p><p>How Are You: ' + name.value +
    '';
  document.getElementById('test').innerHTML = str;
};
<label>
    Your Name: 
    <input id="name" />
</label>
<br />
<button onclick="setTimeout(yes, 7000)">Test</button> <!-- timeout -->
<p id="test"></p>

2 Answers

It's better to attach eventListeners via javascript (instead of the inline onclick) - and in this case, it affords us a lovely opportunity to do the Please Wait... insertion - which gets overwritten (desirably) when the finished output arrives.

window.addEventListener('load', ()  => {
  document.querySelector('button.test-btn').addEventListener('click', e => {
    document.querySelector('#test').innerHTML = '<h3>Please Wait...</h3>';
    setTimeout(yes, 7000)
  })
})

function yes() {
  var button = document.getElementById('test');
  var name = document.getElementById('name');
  var age = document.getElementById('age');
  var location = document.getElementById('location');
  var str = 'Hello! <p> My name is Ashish</p><p>How Are You: ' + name.value +
    '';
  document.getElementById('test').innerHTML = str;
};
<label>
    Your Name: 
    <input id="name" />
</label>
<br />
<button class='test-btn'>Test</button>
<p id="test"></p>

Move the setTimeout to inside the click

I also suggest addEventListener to not have inline event handlers

window.addEventListener("load", function() {
  document.getElementById("test").addEventListener("click", function() {
    console.log("clicked on Test-Button");
    const wait = document.getElementById('wait');
    wait.removeAttribute("hidden")
    setTimeout(function() {
      const name = document.getElementById('name'),
        age = document.getElementById('age'),
        str = '<p>Hello!<br/>My name is Ashish</p><p>How Are You ' + name.value + '?</p>';
      wait.setAttribute("hidden", true)
      document.getElementById('test').innerHTML = str;
    }, 7000);
  });
});
<label>
    Your Name: 
    <input id="name" />
</label>
<br />
<button type="button" id="test">Test</button>
<!-- timeout --><span id="wait" hidden>Please wait</span>
<p id="test"></p>

Related