javascript - 在 JavaScript 中动画递归回溯算法
问题描述
我一直在尝试在递归函数中为回溯算法中的颜色变化设置动画。截至目前,当我运行该函数时,它仅在函数结束时更新颜色。
我在网上阅读了几篇文章,我认为这个问题的发生是因为它是同步运行的,而我需要异步运行它。
我在函数内部尝试了 setTimeout,但是它只会导致浏览器等待设定的时间,然后同时更新所有内容。
我现在将皇后区设置在有效位置,然后当我发现这些位置不再有效时,我使用 myFunction 将它们改回原来的颜色。
我对javascript有点陌生,所以任何见解都会有所帮助,谢谢。
function myFunction(name, color) {
document.getElementById(name).style.background = color;
}
function NQueen(col) {
if (col == n) {
return true;
}
// Checks if given move is valid for all positions in the column
for (var i = 0; i < n; i++) {
let square = "square" + i + col;
if (isValid(i,col)) {
board[i][col] = 1;
let originalColor = document.getElementById(square).style.background;
//setTimeout(function() {myFunction(square, color)}, 2000);
myFunction(square, "rgb(255,0,0)");
if (NQueen(col+1)) {
return true;
}
myFunction(square, originalColor);
board[i][col] = 0;
}
}
return false;
}
编辑
我想我想出了一个解决方法,我制作了具有正方形名称和颜色的对象,并将它们放入数组中。然后我创建了一个递归函数来更改背景并使用 setTimeout 更新它。这有点奇怪,但它有效
function myFunction(num) {
var name = arr[num].square;
var color = arr[num].color;
document.getElementById(name).style.background = color;
if (num < arr.length) setTimeout(function(){myFunction(num+1)}, 1000);
}
解决方案
推荐阅读
- mongodb - SortByCount 并显示每个文档
- bash - 如何正确地将 Bash 数组分配给另一个变量?
- jquery - 选择带有“是”字样的列表选项时尝试显示 Div - Woocommerce
- events - Acumatica - 调用删除事件时更新其他订单的最佳解决方案是什么?
- postgresql - Postgres 对特定数据进行匿名/随机化所有具有数据域的数据
- arrays - perl - 访问数组数组哈希中的元素
- reactjs - 网站首次加载时反应状态未准备好
- import - 没有名为“Self”的模块
- python - Selenium Chrome 驱动程序显示未指定路径
- angular - 使用 Angular CDK 将容器拖到不同的 div