Settimeout func

Hello
I would like to make a picture appear and disappear with settimeout in javascript.
That code makes it disappear. How can I make it appear again and then disappear again?


1 <!DOCTYPE html>
2 <html lang="en">   
 3 <head>
 4 <meta charset="UTF-8" />
 5 <meta http-equiv="X-UA-Compatible" content="IE=edge" />
 6 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
 7<title>Document</title>
 8 <style>
 9 #image {
 10 display: block;
 11 width: 300px;
 12 height: 300px;
 13 }
 14 </style>
  15 </head>
  16 <body>
    17 <img id="image" src="some picture" ; />
    18 <script>
      19 let image = document.querySelector("#image");
      20 setTimeout(function () {
        21 image.style.display = "none";
      22 }, 3000);
    23 </script>
  24 </body>
25 </html>

Thanks for any suggestion :grinning:

If it would be able to do it 10 times, that would be nice.
thanks

I want to do it with a given timeframe. In every minute for example.

Ok. Thanks for your help. :+1:

Thanks. I will do it. :smiley:

To achieve this kind of functionality you should modify your code like this:

 let image = document.querySelector("#image");

    function toggleImage() {
      if (image.style.display === "none") {
        image.style.display = "block";
      } else {
        image.style.display = "none";
      }

      setTimeout(toggleImage, 3000);
    }

    setTimeout(toggleImage, 3000);

But this code needs to be optimized in a proficient way otherwise can occur issue.
To do that you must have a good understanding of the setTimeout function, call stack, and recursion.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.