【发布时间】:2020-01-16 12:41:11
【问题描述】:
我是 JS 的菜鸟,我开始习惯基础知识,但我正在努力将一个变量从一个已经在一个函数中的函数中传递给另一个函数。
我查找了范围并声明了一个全局变量,但是当我在控制台登录时它显示未定义。这是我的代码。 该项目是一个条形图,以百分比显示您在工作中的轮班时间。
我需要将百分比变量从定时循环中传递到 moveLoadingBar 函数中,这样栏会随着时间的推移慢慢向上移动。我错过了什么?
const target = 100; //percent
let percentage;
function setup() {
//Set the start point for today at 09:00:00am
let start = new Date();
start.setHours(9, 00, 00);
setInterval(timeConversion, 1000);
function timeConversion() {
//Work out the difference in miliseconds from now to the start point.
let now = new Date();
let distance = now -= start;
// Time calculations for hours, minutes and seconds
let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((distance % (1000 * 60)) / 1000);
let miliseconds = distance;
//Percentage of day complete **** struggling to pass variable to global variable ****
percentage = (miliseconds / target) * 100
}
}
function moveLoadingBar() {
let loadingBar = document.getElementById("myBar");
let id = setInterval(frame, 1000);
function frame() {
if (percentage >= target) {
clearInterval(id);
} else {
loadingBar.style.width = percentage + "%";
}
}
}
//debugging
setup();
moveLoadingbar();
console.log(percentage);
console.log(target);
CSS
#myProgress {
width: 100%;
background-color: #ddd;
}
#myBar {
width: 1%;
height: 30px;
background: linear-gradient(90deg, #00C9FF 0%, #92FE9D 100%);
}
HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<title>Hello world</title>
</head>
<body>
<h1>Progress Bar</h1>
<div id="myProgress">
<div id="myBar"></div>
</div>
<br>
</body>
<script src="index.js"></script>
</html>
【问题讨论】:
-
尝试将百分比设为 var,避免使用 let 阻止范围界定
标签: javascript loops datetime scope global-variables