输入上的Javascript变量更新

时间:2017-05-29 23:23:19

标签: javascript html

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

更新一个参数
    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完成,但是我必须为这么简单的事情做这件事吗?任何提示赞赏。 HEre的HTML:

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

1 个答案:

答案 0 :(得分:2)

您需要取消任何正在运行的计时器,然后再启动一个新的计时器并使用与之关联的新时间。此外,您的代码需要分开一点。

// 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>