setInterval无法与我的功能一起使用

时间:2018-06-21 22:57:13

标签: javascript setinterval

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

second_hand = document.getElementById('second_hand');

我有一个function可以抽空。

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

  return second;
}

然后我有一个function来旋转手。

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

然后我使用setInterval每秒更新一次rotateHand()

setInterval(rotateHand(second_hand), 1000); 

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

这是此版本:

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>

3 个答案:

答案 0 :(得分:3)

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

您可以:

  • 传递对匿名函数的引用,该匿名函数将使用secondHand参数调用rotateHand

  • 使用Function.prototype.bind以secondHand作为参数将函数引用传递给setInterval(function () { rotateHand(second_hand)}, 1000);

rotateHand
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);

答案 1 :(得分:0)

问题可能与以下行有关:

setInterval(rotateHand(second_hand), 1000); 

rotateHand(second_hand)计算为未定义。因此,您的setInterval没有执行任何操作。

相反,请尝试以下操作:

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

或不含箭糖的等效物:

setInterval(function(){rotatehand(second_hand)},1000);

答案 2 :(得分:0)

使用它,它应该可以工作:

React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

function(){rotateHand(second_hand);}不是函数引用,因此无法使用。

rotateHand(second_hand);
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);