admin管理员组

文章数量:1399963

I'm interested to know if there's a possibility to execute a display='none' after a setTimeout.

The following vanilla JavaScript runs well, but I would like refactoring for a better maintenance.

<div id="id200" style="padding: 7%; text-align: center; background: #87BBBB; color: #FFF;">
Thanks for mailing us
</div>

<div id="id300" style="padding: 20px; background: #000; color: #FFF;">
LOGO
</div>

        <script>
        setTimeout(
            function(){
                document.getElementById("id200").style.opacity = 0;
                document.getElementById("id200").style.transition = "opacity " + 3 + "s";
            }, 3000
        );
        setTimeout(
            function(){
                document.getElementById("id200").style.display='none';
            }, 6000
        );
        </script>

I'm interested to know if there's a possibility to execute a display='none' after a setTimeout.

The following vanilla JavaScript runs well, but I would like refactoring for a better maintenance.

<div id="id200" style="padding: 7%; text-align: center; background: #87BBBB; color: #FFF;">
Thanks for mailing us
</div>

<div id="id300" style="padding: 20px; background: #000; color: #FFF;">
LOGO
</div>

        <script>
        setTimeout(
            function(){
                document.getElementById("id200").style.opacity = 0;
                document.getElementById("id200").style.transition = "opacity " + 3 + "s";
            }, 3000
        );
        setTimeout(
            function(){
                document.getElementById("id200").style.display='none';
            }, 6000
        );
        </script>
Share Improve this question asked Dec 13, 2019 at 6:09 ViDiVeViDiVe 1341 silver badge10 bronze badges 2
  • 2 Fire a second setTimeout from within the first? – evolutionxbox Commented Dec 13, 2019 at 6:14
  • It would be a fine solution, but the transitionend event, suggested by @Constantin, works perfectly – ViDiVe Commented Dec 13, 2019 at 19:26
Add a ment  | 

1 Answer 1

Reset to default 9

You can use the transitionend event instead of a static timer that you'd have to adapt when changing the transition duration:

setTimeout(
  function() {
    var id200 = document.getElementById("id200");
    id200.style.transition = "opacity " + 3 + "s";
    id200.style.opacity = 0;
    id200.addEventListener("transitionend", function() {
      console.log("transition has ended, set display: none;");
      id200.style.display = "none";
    });
  }, 3000
);
<div id="id200" style="padding: 7%; text-align: center; background: #87BBBB; color: #FFF;">
  Thanks for mailing us
</div>

<div id="id300" style="padding: 20px; background: #000; color: #FFF;">
  LOGO
</div>

本文标签: javascriptHow to execute a displaynone after a fadeout setTimeoutStack Overflow