Home > Net >  Run once then repeat a script
Run once then repeat a script

Time:06-02

I've written the following which successfully repeats the script in 5 second intervals. However, I'd like it to start without a 5 second delay. Is ti possible to run the script once without the delay, then start it?

<body onl oad="Run()">


 
<p id = "Text" style =
    "text-align:right; font-size: 100%; font-weight: bold; font-style: italic; color: black; font-family:poppins;">
</p>
 
<script>
 
    var down = document.getElementById('Text');         
    var arr = [
      "\"The end of the liver and the beginning of reading.\"",
      "\"The most straight geniuses intent lemur sand,\"",
      "\"Passim abandonment to fashion,\"",
         
              ];
     
     
 setInterval(function Run() {
        down.innerHTML =
            arr[Math.floor(Math.random() * arr.length)];
  }, 5000) </script>

CodePudding user response:

Sorry, if I interrupted your little cat and mouse game here ;-)

The following snippet contains a few corrections that will make the script work:

  • I defined the function Run() independently of the setInterval() call
  • and then refer to it as the callback function for setInterval().

function Run() {
 down.innerHTML=arr[Math.floor(Math.random() * arr.length)]; }  
const down= document.getElementById('Text');         
const arr = ["hello","goodbye","and whatever","I wanted to say"];
        
setInterval(Run,500);
<body onl oad="Run()">     
<p id = "Text" style =
    "text-align:right; font-size: 100%; font-weight: bold; font-style: italic; color: black; font-family:poppins;">
</p>
 

Ok, I also reduced the interval time too to make it all a bit livelier...

In SO snippets the <script> portion will always be called after the HTML section has been loaded. This is of course something you must make sure in your own document structures.

  • Related