0

I'm trying to make a function that will repeat itself every x seconds, but I'm not sure it's repeating. My code:

function myfunction() {
  if (nonimportant) {
    do something;
  }
  else {
    do something else;
  }
  setTimeout(myfunction(),1000);
}

3 Answers3

2

This is the perfect use case for .setInterval()(Scroll down to the setIntervall() part below setTimeout())

var myVar = setInterval(myTimer, 1000);

function myTimer() {
  var d = new Date();
  var t = d.toLocaleTimeString();
  console.log(t);
}
Aalexander
  • 4,987
  • 3
  • 11
  • 34
0

Take the () out:

function myfunction() {
  if (nonimportant) {
    do something;
  }
  else {
    do something else;
  }
  setTimeout(myfunction,1000);
}

https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout

Jordan
  • 194
  • 1
  • 12
-1

Typical error: you pass the result of the function instead of the function itself to the setTimeout:

function myfunction() {
  if (nonimportant) {
    do something;
  }
  else {
    do something else;
  }
  setTimeout(myfunction,1000);  //notice there's no brackets
}
Mario Vernari
  • 6,649
  • 1
  • 32
  • 44
  • "Typical error:" Answering a duplicate. Instead, vote to close as a duplicate. – Heretic Monkey Jan 28 '21 at 16:11
  • @HereticMonkey I agree that it can be a duplicate, but why only my answer was downvoted? – Mario Vernari Jan 28 '21 at 16:13
  • You have enough rep to vote to close. The other person with enough rep suggested a different approach, which is fine, although still makes it harder to delete the question. – Heretic Monkey Jan 28 '21 at 16:15
  • what? different approach??? the code is exactly the same: check all the answers! – Mario Vernari Jan 28 '21 at 16:17
  • I did. Apparently *you're* missing the difference between `setInterval` and `setTimeout`. But I'm done. You got one downvote which reduced your number of imaginary internet points by an infinitesimal amount. Learn the lesson or don't. – Heretic Monkey Jan 28 '21 at 16:23