我目前有以下代码:
<div id="resource1"></div>
<div id="resource2"></div>
<div id="resource3"></div>
<script>
var resource1 = 50;
var resource2 = 50;
var resource3 = 50;
var modifier = 3;
function resourcesupdates() {
setInterval(function() {
resource1 = resource1 + modifier;
resource2 = resource2 + modifier;
resource3 = resource3 + modifier;
document.getElementById('resource1').innerText = resource1;
document.getElementById('resource2').innerText = resource2;
document.getElementById('resource3').innerText = resource3;
console.log(resource1);
}, 1000);
}
resourcesupdates();
</script>
此代码有效,因为资源每秒更新3次。
如果我想让它以每分钟47的速率更新怎么办,但是我希望它只在资源被整数更新时输出给用户,而不是每秒都会输出,因为这会导致十进制值?
答案 0 :(得分:3)
更新的答案
<div id="resource1"></div>
<div id="resource2"></div>
<div id="resource3"></div>
<script>
var resource1 = 50;
var resource2 = 50;
var resource3 = 50;
var modifier = 47/60;
function resourcesupdates() {
document.getElementById('resource1').innerText = resource1;
document.getElementById('resource2').innerText = resource2;
document.getElementById('resource3').innerText = resource3;
setInterval(function() {
resource1 = resource1 + modifier;
resource2 = resource2 + modifier;
resource3 = resource3 + modifier;
if (Number.isInteger(resource1) ) {
document.getElementById('resource1').innerText = resource1;
}
if (Number.isInteger(resource2) ) {
document.getElementById('resource2').innerText = resource2;
}
if (Number.isInteger(resource3) ) {
document.getElementById('resource3').innerText = resource3;
}
console.log(resource1);
}, 1000);
}
resourcesupdates()
</script>
这是jsFiddle:https://jsfiddle.net/jamesbr139/jf0e3b6u/ 只是还没有看到它更新整数...
答案 1 :(得分:3)
正如我在上面的评论中所述:问题是,当每秒更新47/60时,您可能永远不会达到数字没有小数位的点。如果它仍然符合您的要求,当数字总是四舍五入显示时,这可能是您的解决方案:
var resource1 = 50;
var resource2 = 50;
var resource3 = 50;
var modifier = 47; // per minute
function resourcesupdates() {
setInterval(function() {
resource1 = resource1 + modifier/60;
resource2 = resource2 + modifier/60;
resource3 = resource3 + modifier/60;
document.getElementById('resource1').innerText = Math.round(resource1);
document.getElementById('resource2').innerText = Math.round(resource2);
document.getElementById('resource3').innerText = Math.round(resource3);
}, 1000);
}
resourcesupdates();
&#13;
<div id="resource1"></div>
<div id="resource2"></div>
<div id="resource3"></div>
&#13;
如果您希望按照对其他问题的评论中的要求始终向下舍入,只需将Math.round()
替换为Math.floor()
。