Fresh
Fresh

Reputation: 51

Reset after certain time JavaScript

I'm trying to learn JavaScript and I'm wondering how to reset a function after say 5 seconds.

function myFunction() {
  document.getElementById("demo1").innerHTML = "Now you 've learnt some JavaScript.";
}
document.getElementById('demo1').reset()
p {
  background-color: red;
}

button {
  background-color: yellow;
}
<p id="demo1">1st Lesson</p>
<button type="button" onclick="myFunction()">Try it</button>

As you can see, I've used .reset but a) it doesn't work and b) don't know how to assign timing function.

Upvotes: 1

Views: 1143

Answers (2)

RIR360
RIR360

Reputation: 99

So, you want to reset your #demo1 element's innerHTML after 5 seconds? Ok... To do that, use this JavaScript code:

function myFunction() {  
   const demo = document.getElementById("demo1");
   const initialText = demo.innerText;
   demo.innerText = "Now you've learnt some JavaScript.";

   setTimeout(() => {
	   demo.innerText = initialText;
   }, 5000);
}
p {
  background-color: red;
}

button {
  background-color: yellow;
}
<p id="demo1">1st Lesson</p>
<button type="button" onclick="myFunction()">Try it</button>

Here, setTimeout is something that you need to do something after some desired time. (5000ms = 5s)

Upvotes: 3

Leftium
Leftium

Reputation: 17903

It seems the reset() method only works on form elements (for example, a text input or checkbox.) In fact, the reset method doesn't exist for a <p> element, so your code probably results in an error (check the browser dev console for the error message.)

To fix this, change element demo1 to a form input element (you may also have to add a default value attribute).

Alternatively, you can change the way you "reset" the value. Just manually set the contents of the <p> back to the original value.

Finally use setTimeout() to delay execution. Here is code that accomplishes your goal. (Hit the blue "Run code snippet" button to try it out!)

function myFunction() {  
    // Save the HTML to "reset" later
    originalInnerHTML = document.getElementById("demo1").innerHTML

    document.getElementById("demo1").innerHTML = "Now you've learnt some JavaScript.";
      
    setTimeout(function() {
        // Instead of
        // document.getElementById ('demo1').reset()
        // do this:
        document.getElementById("demo1").innerHTML = originalInnerHTML;
    }, 5000);
    
} 
P { background-color:red; } 

button {background-color: yellow; } 
<p id="demo1">1st Lesson</p>

<button type="button" onclick="myFunction()">Try it</button>

Upvotes: 1

Related Questions