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

标签 javascript html setinterval

我想知道一种更改 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/

相关文章:

javascript - 通过 CSS/Javascript 右下角叠加

javascript - 将数据从 HTML 输入文本元素传递到 JavaScript 变量

javascript - 在鼠标悬停时更改映射图像热点的背景

html - 如何找到所有以 "<tr"结尾的表达式(stringi 包)

Javascript SetInterval() 作用域问题

javascript - 在 querySelector 中使用 php 变量

javascript - 如何通过数组将 HTML 元素附加到按钮

pdf 中不支持的 HTML 样式标签

javascript - 一个 SetInterval 与多个 SetTimeout

javascript - 如何无限重复javascript setInterval计时器两次