Home > OS >  How do you stop displaying a div element (id) after a certain amount of time?
How do you stop displaying a div element (id) after a certain amount of time?

Time:10-19

I have been coding a website, but I want a message to disappear/not display after a few seconds. I tried different code snippets but I cannot seem to plug them in properly with my code. Is there any way I could make it stop displaying after a certain amount of time?

var done = "Done!";
document.getElementById("done").innerHTML = done;

var startTime = new Date().getTime();
var interval = setInterval(function() {
  if (new Date().getTime() - startTime > 2000) {
    clearInterval(interval);
    return;
  }
  done.getElementById.remove("done");
}, 2000);
<h2 style="color:green;" id="greendisp">
  <span id="done"></span>
</h2>

CodePudding user response:

You should use setTimeout

const done = "Done!";
document.getElementById("done").innerHTML = done;

setTimeout(() => {
  document.getElementById("done").remove()
}, 2000)
<h2 style="color:green;" id="greendisp"><span id="done"></span></h2>

CodePudding user response:

Try this.

This will use a timeout instead of an interval.

// Element to remove
const targetId = 'done';
// Set HTML of element with id 'done' to 'Done!'
document.getElementById(targetId).innerHTML = "Done!";

// Set a Timeout which will call the function inside after 2000ms (2 seconds)
setTimeout(function () {
    // Remove the target element with id 'done'
    document.getElementById(targetId).remove();
}, 2000);
<h2 style="color:green;" id="greendisp"><span id="done"></span></h2>

  • Related