setInterval 不适用于我的函数

oeh*_*aut 1 javascript setinterval

我正在尝试构建一个模拟时钟。

second_hand = document.getElementById('second_hand');
Run Code Online (Sandbox Code Playgroud)

我有一个function,得到时间。

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

  return second;
}
Run Code Online (Sandbox Code Playgroud)

然后我有一个function旋转手。

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

然后我使用 asetInterval来更新我的rotateHand()每一秒。

setInterval(rotateHand(second_hand), 1000); 
Run Code Online (Sandbox Code Playgroud)

但是我的手不是每秒更新(移动)。怎么了?

这是一个版本:

second_hand = document.getElementById('second_hand');
Run Code Online (Sandbox Code Playgroud)
function getTime() {
  var date = new Date(),
  second = date.getSeconds();

  return second;
}
Run Code Online (Sandbox Code Playgroud)

Gui*_*ges 6

setInterval需要一个函数引用作为第一个参数。您不是在传递函数引用,而是在调用该rotateHand函数。

你可以:

  • 传递对匿名函数的引用,该函数将rotateHand使用 secondHand 参数调用:setInterval(function () { rotateHand(second_hand)}, 1000);

  • 使用Function.prototype.bind将函数引用传递rotateHand给以 secondHand 作为参数:

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);
Run Code Online (Sandbox Code Playgroud)
<div id="second_hand">2nd hand</div>
Run Code Online (Sandbox Code Playgroud)

  • `call` 不是立即运行函数,使用`bind` 不是更有意义吗? (2认同)
  • @FredStark `bind` 就是我的意思。感谢您指出了这一点。我编辑了。 (2认同)