0

I have a couple of code snippets. Basically, I want to need that when a user clicks on the button the output which comes should be delay by 2-5second. more convenient if text come please wait... on clicking the button(but not in the button text). or "loading image" like preloader.

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');
  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="yes()">Test</button>
<p id="test"></p>

0

1 Answer 1

1

Use a delay function const delay = (dur) => new Promise((r) => setTimeout(r, dur)); to get something like this:

const delay = (dur) => new Promise((r) => setTimeout(r, dur));

async function yes() {
  var button = document.getElementById('test');
  var name = document.getElementById('name');
  var age = document.getElementById('age');
  var location = document.getElementById('location');
  document.getElementById('test').innerHTML = "Please wait a while ...";
  await delay(1000);
  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="yes()">Test</button>
<p id="test"></p>

or a simple timeout setTimeout(yes, 1000):

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, 1000)">Test</button> <!-- timeout -->
<p id="test"></p>

Sign up to request clarification or add additional context in comments.

3 Comments

Please don't duplicate answers. If a question has been answered before, flag it to be marked as a duplicate.
How Can I add please wait A while... text when the user click on button
See the edit on the first snippet!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.