gpt4 book ai didi

javascript - setInterval 不适用于我的函数

转载 作者:行者123 更新时间:2023-11-28 17:28:34 24 4
gpt4 key购买 nike

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

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>

最佳答案

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

您可以:

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

  • 使用Function.prototype.bind以 secondaryHand 作为参数将函数引用传递给 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);
<div id="second_hand">2nd hand</div>

关于javascript - setInterval 不适用于我的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50978493/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com