gpt4 book ai didi

输入时 JavaScript 变量更新

转载 作者:行者123 更新时间:2023-12-01 03:36:26 25 4
gpt4 key购买 nike

我有一个函数,我试图根据范围输入的值更新一个参数

    a.start = function () {
var t = 50;
var rangeInput = document.getElementById('speed');
rangeInput.addEventListener("change", function () {
t = document.rangeInput.value;});
setInterval(function () {
a.update();
a.draw();
}, t );

};

老实说,我很沮丧,因为我无法让这个函数动态工作。它以某种方式简单地与

  a.start = function () {
var t = document.getElementById('speed');
setInterval(function () {
a.update();
a.draw();
}, t );

};

但只有在我刷新页面之后。老实说,我对javascript的理解很差,我知道可以使用AJAX来完成,但是这么简单的事情我必须这样做吗?任何提示表示赞赏。这是 html:

 <form>
<label for="speed">
<input id="speed" type="range" name="points" min="10" max="2000" >Animation speed</label>
</form>

最佳答案

您需要先取消任何正在运行的计时器,然后才能启动具有与其关联的新时间的新计时器。另外,您的代码需要稍微分开。

// Place all this code at the bottom of the code, just before the </body>

var rangeInput = document.getElementById('speed');
var t = 500; // Default
var timer = null; // Reference to the interval timer

rangeInput.addEventListener("change", function(){
t = rangeInput.value;

// Cancel any previous timers
clearInterval(timer);

// Do the animation every t milliseconds
timer = setInterval(function(){
// Commented out only because we don't know what "a" is:
//a.update();
//a.draw();

// For debugging:
console.log(t);
}, t);
});
<form>
<label for="speed">
<input id="speed" type="range" name="points" min="10" max="5000" >Animation speed</label>
</form>

您还可以使用 setTimeout() 而不是 setInterval() 来完成此操作:

// Place all this code at the bottom of the code, just before the </body>

var rangeInput = document.getElementById('speed');
var t = 500; // Default
var timer = null; // Reference to the interval timer

rangeInput.addEventListener("change", animate);

function animate(){
clearTimeout(timer);

t = rangeInput.value;

// Commented out only because we don't know what "a" is:
//a.update();
//a.draw();

// For debugging:
console.log(t);

// Do the animation every t milliseconds. Call the function recursively
timer = setTimeout(animate, t);
}
<form>
<label for="speed">
<input id="speed" type="range" name="points" min="10" max="5000" >Animation speed</label>
</form>

关于输入时 JavaScript 变量更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44251348/

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