Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use time intervals in the function?

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();
like image 583
mehmet Avatar asked Oct 15 '25 17:10

mehmet


2 Answers

You can use setTimeout

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

Or setInterval

function writeNow() {
  document.write('q');
}
setInterval(() => {
  writeNow()
}, 1000);
like image 187
Gopal Avatar answered Oct 18 '25 05:10

Gopal


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

like image 27
Da Mahdi03 Avatar answered Oct 18 '25 07:10

Da Mahdi03



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!