Josh
Josh

Reputation: 33

toggle button text on a timer with javascript

I have a working toggle button text code but I would like the button to toggle back to the original state after 4 seconds.

I have tried looking for a solution and can't wrap my head around whether I need to use a setInterval function or setTimeout function and how to implement them exactly.

Hopefully, a javascript wizard can help me out here.

function myFunctionbutton() {
  var x = document.getElementById("singleadd");
  if (x.innerHTML === "add to bag") {
    x.innerHTML = "Loading...";
  } else {
    x.innerHTML = "add to bag";
  }
}
<button id="singleadd" onclick="myFunctionbutton()">add to bag</button>

Upvotes: 3

Views: 714

Answers (3)

Not A Robot
Not A Robot

Reputation: 2684

You can use setTimeout() function to get back to "add to bag" state after 4 seconds.

Also, if you want you can disabled the button for that 4 seconds, so that the user cannot click again untill 4 seconds are over.

function myFunctionbutton() {
  var x = document.getElementById("singleadd");
  x.disabled = true;
  x.innerText = "Loading...";
  setTimeout(() => {
     x.innerText = "add to bag";
     x.disabled = false;
  }, 4000);
  
}
<button id="singleadd" onclick="myFunctionbutton()">add to bag</button>

Upvotes: 1

Sudhir Ojha
Sudhir Ojha

Reputation: 3305

You can use setInterval and provide interval in miliseconds.

function myFunctionbutton() {
  var x = document.getElementById("singleadd");
  if (x.innerHTML === "add to bag") {
    x.innerHTML = "Loading...";
  } 
  setInterval(function(){ x.innerHTML = "add to bag"; }, 4000);
}
<button id="singleadd" onclick="myFunctionbutton()">add to bag</button>

Upvotes: 1

wangdev87
wangdev87

Reputation: 8751

You can use setTimeout()

function myFunctionbutton() {
  var x = document.getElementById("singleadd");
  if (x.innerHTML === "add to bag") {
    x.innerHTML = "Loading...";
    setTimeout(function () {
      x.innerHTML = "add to bag"
    }, 4000);
  }
}
<button id="singleadd" onclick="myFunctionbutton()">add to bag</button>

Upvotes: 2

Related Questions