soyaine/JavaScript30

02 纯 JS、CSS 时钟 计算的时候建议加入取余运算,避免长时候运行后,数值大小溢出

Closed this issue · 1 comments

在解决秒针突然跳动的 方法二中的

function updateDate() {
	secondDeg += (1 / 60) * 360;
	minDeg += ((1 / 60) / 60) * 360;
	hourDeg += (((1 / 60) / 60) / 12);
	
	secHand.style.transform = `rotate(${ secondDeg}deg)`;
	minHand.style.transform = `rotate(${ minDeg }deg)`;
	hourHand.style.transform = `rotate(${ hourDeg }deg)`;
}

建议改成

function updateDate() {
	secondDeg = (secondDeg + (1 / 60) * 360) % 360;
	minDeg = (minDeg + ((1 / 60) / 60) * 360) % 360;
	hourDeg = (hourDeg + (((1 / 60) / 60) / 12)) % 360;
	
	secHand.style.transform = `rotate(${ secondDeg}deg)`;
	minHand.style.transform = `rotate(${ minDeg }deg)`;
	hourHand.style.transform = `rotate(${ hourDeg }deg)`;
}

后来想到 JS数据精度的问题, 在运算中会不断累计误差, 如果要长期运行的话,
我会选择每次重新运算, 而不是累加的方式,选择方案一