0

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...

11
  • 1
    setInterval(function, 1000); Call function at every 1 second. Commented Mar 8, 2019 at 2:52
  • well you would need to change the number of degrees.... You set it to the same thing every time. Commented Mar 8, 2019 at 2:52
  • @Ajay the code above is fine with the timeout.... Commented Mar 8, 2019 at 2:57
  • 5
    oh god please stop i'm getting dizzy Commented Mar 8, 2019 at 2:57
  • 1
    Why not use a css animation, no JavaScript necessary. Commented Mar 8, 2019 at 4:01

2 Answers 2

2

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)' 
Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.