Topher
Topher

Reputation: 151

How do I call a function every whatever seconds in Javascript?

Not sure why this is so hard to do in Javascript... Slightly frustrating LOL

Here's one of the ways I've tried to do it:

function rotateDavid() {
  $("#david").css({
    'transform' : 'rotate(90deg)'
  });
  setTimeout(rotateDavid, 10000);
};
rotateDavid();

It will do it once but doesn't repeat... I dunno...

Upvotes: 0

Views: 243

Answers (2)

epascarello
epascarello

Reputation: 207501

The problem here is not how you are calling the function. This way is actually preferred over setInterval in some cases.

The issue you have is that setting the Css to 90degrees is not changing it over and over. You are setting it to the same degree value every time.

You need to update the angle on every iteration. So in this case you want to add 90 to it.

var rotation = 0;
function rotateDavid() {
  rotation += 1
  $("#david").css({
    'transform' : 'rotate(' + (90 * rotation) + 'deg)'
  });
  setTimeout(rotateDavid, 1000);
};
rotateDavid();
div{
  width:100px;
  height: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="david">Hi</div>

You can also use a mod operator to keep the number from getting huge.

'transform' : 'rotate(' + (90 * (rotation%4)) + 'deg)'

Upvotes: 2

Shidersz
Shidersz

Reputation: 17190

Your method, actually, is called every 10s. You can check it if you add a log to the console inside the method. However, you was setting the css property always to the same value, so you won't see any visual effect. A possible fix is shown on next example:

function rotateDavid(rot)
{
  $("#david").css({
    'transform': `rotate(${rot}deg)`
  });

  rot = rot + 90 >= 360 ? 0 : rot + 90;
  setTimeout(() => rotateDavid(rot), 5000);
};

rotateDavid(0);
#david {
  background: skyblue;
  width: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="david">David</div>

Even more, you can get similar functionality using setInterval():

function rotateDavid(rot)
{
  $("#david").css({
    'transform': `rotate(${rot}deg)`
  });
};

var rot = 90;
setInterval(
  () => {rotateDavid(rot); rot = rot + 90 >= 360 ? 0 : rot + 90;},
  5000
);
#david {
  background: skyblue;
  width: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="david">David</div>

Upvotes: 0

Related Questions