我正在尝试通过滑块控制画布对象的速度。问题在于画布正在从ajax调用中读取数据,我似乎无法通过页面上的滑块访问timeout变量来更改速度。
我删除了所有无效的代码。 我将其恢复为上一个工作版本,其中没有带有setTimeout速度的硬编码值的滑块值。
$.ajax({
url: "/static/Data/test.txt",
dataType: "text",
cache: false,
async: true,
success: function (data) {
var arr = data.split(/,/g).slice(0);
function drawShape(x , y,colour){
context.strokeRect(p + gridX,p,gridX,gridY);
context.fillStyle = colour;
context.fillRect(p + gridX * x,p+ gridY * y,gridX,gridY);
}
for(let i=0; i<arr.length -2; i+=2){
window.setTimeout(function () {
x1 = arr[i];
y1 = arr[i+1];
context.clearRect(0, 0, 650, 650);
drawBoard();
if(grid_type == "grid_standard") {
drawShape(5, 0, 'green');
drawShape(5, 1, 'red');
drawShape(4, 3, 'red');
drawShape(4, 4, 'red');
drawShape(2, 2, 'red');
drawShape(2, 3, 'red');
drawShape(y1, x1, 'yellow');
}
if(grid_type == "grid_cliff") {
drawShape(5, 5, 'green');
drawShape(4, 5, 'red');
drawShape(3, 5, 'red');
drawShape(2, 5, 'red');
drawShape(1, 5, 'red');
drawShape(y1, x1, 'yellow');
}
// $("body").append("Pos: " + x1 + " "+y1);
}, i * 50);
}
//console.log($.unique(position));
// $("#div1").text(data);
}
});
任何指针将不胜感激。
答案 0 :(得分:0)
如果要更改持续时间,则需要清除当前超时并创建新的超时。通常最好使用reguestAnimationFrame https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame并结合使用从中获得的时差和设置的速度来确定每个帧中的更改量。
如果要使用setTimeout,可以执行类似var timeout = window.setTimeout(rest of your code
的操作
并在更改值clearinterval(timeout);
并重新创建超时时