gpt4 book ai didi

javascript - 如何通过用户输入更改 setInterval 中的时间?

转载 作者:行者123 更新时间:2023-11-30 19:11:13 25 4
gpt4 key购买 nike

我想知道一种更改 setInterval 时间的方法,以便我的图像以该速度在屏幕上移动。例如,如果我输入 500 毫秒,当我单击一个按钮时,它会将时间间隔从 250 更改为 500。这是我到目前为止的想法。

 var x;
var y;
var timing = 1000;

function window_onLoad() {
x = 0;
y = 100;
window.setInterval("MoveBall()", timing);
picBall.style.top = y + "px";
}
function MoveBall() {
x = x + 5;
if (x < document.body.clientWidth - 91) {
picBall.style.left = x + "px";
}
}
function btnReset_OnClick() {
x = 0;
}
function btnSpeed_OnClick() {
timing = parseInt(txtSpeed.value);
}

window_onLoad()
<img id="picBall" src="Face.jpg" style="position: absolute;"/>
<input id="btnReset" type="button" value="Reset position"
onclick="btnReset_OnClick()"/>
<input id="txtSpeed" type="text"/>
<input id="btnSpeed" type="button" value="Change Speed"
oclick="btnSpeed_onClick()"/>

最佳答案

我建议不要将移动速度与帧率(您的 setInterval 速度)混在一起。您可以拥有固定的帧率和可变的速度。例如

var speed = 1, timer, x,y;


function window_onLoad() {
x = 0;
y = 100;
window.setInterval("MoveBall()", 100); // 10 frames per second
picBall.style.top = y + "px";
}
function MoveBall() {
x = x + speed;
if (x < document.body.clientWidth - 91) {
picBall.style.left = x + "px";
}
}
function btnReset_OnClick() {
x = 0;
}
function btnSpeed_OnClick() {
/*
speed = 200 will move tbe ball by 20px per sec
speed = 100 will move the ball by 10px per sec
speed = 50 will move the ball by 5px per sec
*/
speed = parseInt(txtSpeed.value)/100;
}

关于javascript - 如何通过用户输入更改 setInterval 中的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58449845/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com