Chart.js update() 方法最后只工作一次,而不是每次迭代都更新
Chart.js update() method only works once in the end instead of updating every iteration
function insertSort(inputArray = myChart.data.datasets[0].data) {
let inputArrayLength = inputArray.length;
let outerIndex = 1;
let innerIndex = 0;
while(outerIndex<inputArrayLength) {
innerIndex = outerIndex - 1;
temp = outerIndex;
while(innerIndex>=0){
if (inputArray[temp]<inputArray[innerIndex]){
inputArray[innerIndex] = [inputArray[temp], inputArray[temp] = inputArray[innerIndex]][0];
temp = innerIndex;
innerIndex--;
} else {
innerIndex--;
}
}
sleep(1000);
console.log('Intermediate result is: ', inputArray);
myChart.data.datasets[0].data = inputArray;
myChart.update();
outerIndex++;
}
console.log('Final result is: ', inputArray);
return true;
}
function sleep(milliseconds) {
console.log('going in sleep');
const date = Date.now();
let currentDate = null;
do {
currentDate = Date.now();
} while (currentDate - date < milliseconds);
console.log('out of sleep');
}
let ctx = document.getElementById('myChart').getContext('2d');
let randomArray = Array.from({length: 10}, () => Math.floor(Math.random() * 10+1));
let myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange', 'Blue', 'Blue', 'Blue', 'Blue'],
datasets: [{
label: '# of Votes',
data: randomArray,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(54, 162, 235, 0.2)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<h1>Hello, world!</h1>
<button type="button" onclick="insertSort()">StartSorting</button>
<canvas id="myChart" width="400" height="400">
</canvas>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
我在JavaScript中构建了一个简单的插入排序算法,它对一个包含十个随机整数的数组从小到大进行排序。
- 结果是使用Chart.js库可视化的,十个不同高度的柱被排序并从最短到最高更新。
我现在想要实现的是:可视化这个排序过程的每一步。我引入了一个 sleep() 函数,它基本上延迟了代码执行,紧接着 sleep() 函数,我调用 myChart.update() 来更新柱。但结果不是我所期望的,事实证明所有的条柱在这段代码执行结束时只更新一次,而不是在排序步骤完成时更新。
有人可以帮忙吗?我的代码可以由 C&P 作为 HTML 文件执行,并在 Chrome 浏览器中 运行 执行。点击 startSorting 按钮进行排序,开发者控制台中会提供一些简单的调试信息。
您的代码阻塞了 UI,因此控制台日志消息和更新的图表只能在其执行完成后显示(参见 )。
与其使用您自己的 sleep
函数,不如使用 setTimeout
来安排单独的工作部分。下面的可运行代码说明了当函数 insertSort
被简化并且不再执行它最初所做的事情时它是如何工作的。
function insertSort(inputArray = myChart.data.datasets[0].data) {
let inputArrayLength = inputArray.length;
let outerIndex = 1;
while(outerIndex<inputArrayLength) {
setTimeout(() => {
myChart.data.datasets[0].data = Array.from({length: 10}, () => Math.floor(Math.random() * 10+1));
console.log('Intermediate result is: ', myChart.data.datasets[0].data.join(', '));
myChart.update();
}, 1000 * outerIndex);
outerIndex++;
}
console.log('Final result is: ', inputArray.join(', '));
return true;
}
let ctx = document.getElementById('myChart').getContext('2d');
let randomArray = Array.from({length: 10}, () => Math.floor(Math.random() * 10+1));
let myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange', 'Blue', 'Blue', 'Blue', 'Blue'],
datasets: [{
label: '# of Votes',
data: randomArray,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(54, 162, 235, 0.2)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js"></script>
<button type="button" onclick="insertSort()">StartSorting</button>
<canvas id="myChart" height="100">
function insertSort(inputArray = myChart.data.datasets[0].data) {
let inputArrayLength = inputArray.length;
let outerIndex = 1;
let innerIndex = 0;
while(outerIndex<inputArrayLength) {
innerIndex = outerIndex - 1;
temp = outerIndex;
while(innerIndex>=0){
if (inputArray[temp]<inputArray[innerIndex]){
inputArray[innerIndex] = [inputArray[temp], inputArray[temp] = inputArray[innerIndex]][0];
temp = innerIndex;
innerIndex--;
} else {
innerIndex--;
}
}
sleep(1000);
console.log('Intermediate result is: ', inputArray);
myChart.data.datasets[0].data = inputArray;
myChart.update();
outerIndex++;
}
console.log('Final result is: ', inputArray);
return true;
}
function sleep(milliseconds) {
console.log('going in sleep');
const date = Date.now();
let currentDate = null;
do {
currentDate = Date.now();
} while (currentDate - date < milliseconds);
console.log('out of sleep');
}
let ctx = document.getElementById('myChart').getContext('2d');
let randomArray = Array.from({length: 10}, () => Math.floor(Math.random() * 10+1));
let myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange', 'Blue', 'Blue', 'Blue', 'Blue'],
datasets: [{
label: '# of Votes',
data: randomArray,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(54, 162, 235, 0.2)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<h1>Hello, world!</h1>
<button type="button" onclick="insertSort()">StartSorting</button>
<canvas id="myChart" width="400" height="400">
</canvas>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
我在JavaScript中构建了一个简单的插入排序算法,它对一个包含十个随机整数的数组从小到大进行排序。
- 结果是使用Chart.js库可视化的,十个不同高度的柱被排序并从最短到最高更新。
我现在想要实现的是:可视化这个排序过程的每一步。我引入了一个 sleep() 函数,它基本上延迟了代码执行,紧接着 sleep() 函数,我调用 myChart.update() 来更新柱。但结果不是我所期望的,事实证明所有的条柱在这段代码执行结束时只更新一次,而不是在排序步骤完成时更新。
有人可以帮忙吗?我的代码可以由 C&P 作为 HTML 文件执行,并在 Chrome 浏览器中 运行 执行。点击 startSorting 按钮进行排序,开发者控制台中会提供一些简单的调试信息。
您的代码阻塞了 UI,因此控制台日志消息和更新的图表只能在其执行完成后显示(参见
与其使用您自己的 sleep
函数,不如使用 setTimeout
来安排单独的工作部分。下面的可运行代码说明了当函数 insertSort
被简化并且不再执行它最初所做的事情时它是如何工作的。
function insertSort(inputArray = myChart.data.datasets[0].data) {
let inputArrayLength = inputArray.length;
let outerIndex = 1;
while(outerIndex<inputArrayLength) {
setTimeout(() => {
myChart.data.datasets[0].data = Array.from({length: 10}, () => Math.floor(Math.random() * 10+1));
console.log('Intermediate result is: ', myChart.data.datasets[0].data.join(', '));
myChart.update();
}, 1000 * outerIndex);
outerIndex++;
}
console.log('Final result is: ', inputArray.join(', '));
return true;
}
let ctx = document.getElementById('myChart').getContext('2d');
let randomArray = Array.from({length: 10}, () => Math.floor(Math.random() * 10+1));
let myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange', 'Blue', 'Blue', 'Blue', 'Blue'],
datasets: [{
label: '# of Votes',
data: randomArray,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(54, 162, 235, 0.2)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js"></script>
<button type="button" onclick="insertSort()">StartSorting</button>
<canvas id="myChart" height="100">