Я все еще думаю о JS и начинаю понимать, но я борюсь с setInterval. Я искал ответы в Интернете, но не могу найти решение. Мой проект - это панель загрузки, которая показывает, насколько далеко вы работаете в смену.
У меня есть setInterval для определения расстояния с настоящего момента до 09:00:00 утра в секунду
У меня есть еще один setInterval для обновления ширины полосы загрузки, которая находится в пределах функции в секунду
Мое обоснованное предположение состоит в том, что оба конфликтуют, но мне нужно передать переменные между двумя функциями так, Я не могу их разделить. Я добавил console.log, который будет увеличиваться с 1, 20, 50, 150, 300, 500, 700 и т. Д. Это мешает моей панели загрузки, потому что через некоторое время он пытается loadingBar.style.width = процент.toFixed (4) + "%"; x 1000 в секунду.
Что такое Я пропал?
const target = 100; //percent
let shiftLength = 8.5; //hours
//convert into miliseconds
shiftLength *= 60 * (60 * 1000);
function setup() {
//Set the start point for today at 09:00:00am & now.
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 the day complete
let percentage;
percentage = (miliseconds / shiftLength) * 100;
moveLoadingBar();
function moveLoadingBar() {
let loadingBar = document.getElementById("myBar");
let id = setInterval(frame, 1000);
//pass the percentage to a function that updates the width of the loading bar
function frame() {
if (percentage >= target) {
clearInterval(id);
} else {
loadingBar.style.width = percentage.toFixed(4) + "%";
//The line above and this is being duplicated to the console.
//the longer this code runs the more buggy my bar appears.
console.log("hello");
}
}
}
}
}
setup();
#myProgress {
width: 100%;
background-color: #ddd;
}
#myBar {
width: 1%;
height: 30px;
background: linear-gradient(90deg, #00C9FF 0%, #92FE9D 100%);
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<title>Loading bar project</title>
</head>
<body>
<h1>JavaScript Progress Bar</h1>
<div id="myProgress">
<div id="myBar"></div>
</div>
<br>
</body>
<script src="index.js"></script>
</html>