how to use time intervals in the function?

Viewed 182

I want the letters 'q' to be written only once per second. But it doubles every second. How to do this with this command?

function writeNow() {
   document.write('q');
   setInterval(writeNow, 1000);
}
writeNow();

5 Answers

You can use setTimeout

   function writeNow() {
      document.write('q');
      setTimeout(writeNow, 1000);
    }
    writeNow();

Or setInterval

function writeNow() {
  document.write('q');
}
setInterval(() => {
  writeNow()
}, 1000);

You want to set the interval outside the function, when you call it inside the function, it will be recursive

Try

function writeNow() {
    document.write('q');
}
setInterval(writeNow, 1000);
writeNow();

And I highly recommend against document.write as it is deprecated

But it doubles every second

Because you are calling the setInterval inside the method. So it looks like recursion

Solution:

You should move setInterval(writeNow, 1000); outside the called function - writeNow.


Syntax

setInterval(function, milliseconds, [param1, param2, ...])

function writeNow() {
   document.write('q');
}
setInterval(writeNow, 1000);

Try this

<script>
  function writeNow() {
    document.write('this');
  }
  setInterval(writeNow, 1000);
</script>

You were calling a function recursively

The below code does the job. May be able to fine tune a bit to improve performance:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <style media="screen">
        #letters
        {
            padding: 10px;
            margin: 10px;
        }
    </style>
  </head>
  <body>
    <div id="letters">

    </div>
  </body>

  <script type="text/javascript">
      let alphabets = [];
      let running = false;
      let output = "";

      function prepare()
      {
          for(i=65; i<92; i++)
          {
              console.log(String.fromCharCode(i));
              alphabets.push(String.fromCharCode(i));
          }
      }

      let lastPrinted = 0;

      function printAlphabet()
      {
          if(lastPrinted == 0)
          {
              running = true;
          }
          else if(lastPrinted == 26)
          {
              running = false;
          }

          if(running)
          {
              output += (alphabets[lastPrinted]) + ","
              document.getElementById('letters').innerHTML = output;
              lastPrinted ++;
              setTimeout(printAlphabet, 1000);
          }
          else
          {
              output = output.substring(0,output.length - 1)+".";
              document.getElementById('letters').innerHTML = output;
          }
      }

      prepare();
      printAlphabet();
  </script>

</html>

Output:

A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z
Related