2

I'm trying to build an analog clock.

second_hand = document.getElementById('second_hand');

I have a function that get the time.

function getTime() {
  var date = new Date(),
  second = date.getSeconds();

  return second;
}

Then I have a function that rotate the hand.

function rotateHand(hand) {
  var second = getTime();
  hand.style.transformOrigin = "0 100%";
  hand.style.transform = 'rotate(' + second * 6 + 'deg)';
}

Then I am using a setInterval to update my rotateHand() every second.

setInterval(rotateHand(second_hand), 1000); 

But my hand is not updating(moving) every second. What is wrong?

Here is a version of this:

second_hand = document.getElementById('second_hand');
function getTime() {
  var date = new Date(),
  second = date.getSeconds();

  return second;
}
function rotateHand(hand) {
  var second = getTime();
  hand.style.transformOrigin = "0 100%";
  hand.style.transform = 'rotate(' + second * 6 + 'deg)';
}

setInterval(rotateHand(second_hand), 1000);
<div id="second_hand">hiiiiiiiiii</div>
Sheshank S.
  • 3,053
  • 3
  • 19
  • 39
oehaut
  • 129
  • 2
  • 9

3 Answers3

7

setInterval needs a function reference as the first parameter. You're not passing a function reference, you're invoking the rotateHand function.

You can either :

  • pass a reference to an anonymous function that will call rotateHand with the secondHand parameter : setInterval(function () { rotateHand(second_hand)}, 1000);

  • use Function.prototype.bind to pass a function reference to rotateHand with secondHand as a parameter :

var second_hand = document.getElementById('second_hand');

function getTime() {
  var date = new Date(),
  second = date.getSeconds();

  return second;
}

function rotateHand(hand) {
  var second = getTime();
  hand.style.transformOrigin = "0 100%";
  hand.style.transform = 'rotate(' + second * 6 + 'deg)';
}

setInterval(rotateHand.bind(null, second_hand), 1000);
<div id="second_hand">2nd hand</div>
Guillaume Georges
  • 3,878
  • 3
  • 14
  • 32
2

The issue probably has to do with this line:

setInterval(rotateHand(second_hand), 1000); 

rotateHand(second_hand) evaluates to undefined. So you're setInterval isn't doing anything.

Instead try this:

setInterval(()=>rotateHand(second_hand), 1000); 

Or the equivalent without arrow sugar:

setInterval(function(){rotatehand(second_hand)},1000);
Uzer
  • 3,054
  • 1
  • 17
  • 23
0

Use this, it should work:

function(){rotateHand(second_hand);}

rotateHand(second_hand); isn't a function reference so it won't work.

second_hand = document.getElementById('second_hand');
function getTime() {
  var date = new Date(),
  second = date.getSeconds();

  return second;
}
function rotateHand(hand) {
  var second = getTime();
  hand.style.transformOrigin = "0 100%";
  hand.style.transform = 'rotate(' + second * 6 + 'deg)';
}

setInterval(function(){rotateHand(second_hand);}, 1000);
<div id="second_hand">------------</div>
Sheshank S.
  • 3,053
  • 3
  • 19
  • 39