setInterval 无法按预期工作

setInterval dosn't work as expected

本文关键字:工作 setInterval      更新时间:2023-09-26
function startAutoScrolling() {
     var distance = y2 - y1;
     var speed = distance / dateDiff;
     interval1 = setInterval(function() { doAutoScrolling(speed); }, 1); 
}

在这里我想减少 0.1 的步长但它不是那样工作的,我不知道为什么

function doAutoScrolling(step) {
     document.getElementById(CONTEINER).scrollTop += step;
     if (isGoingDown) {
          step  = step - 0.1;
          console.log("step - 1: " + step); 
          if (step <= 0) {
               clearInterval(interval1); 
          }
     } else  {   // there is continue below

在这里我想增加步骤,如果条件必须停止执行块但它也不起作用

          step += 0.01;
          if (step >= 0) {
               clearInterval(interval1); 
          }
     } 
}

你正在使用Javascript逗号运算符,你很可能想要使用小数,例如:

step  = step - 0,1;

应该是:

step  = step - 0.1;

有关逗号运算符的更多信息:

  • 逗号在 JavaScript 表达式中有什么作用?
  • 逗号运算符何时有用?

更新(逗号到点之后 - 更改(

在 Javascript 中,原语是按值传递的(参见:Javascript 是否通过引用传递?(,所以你基本上是使用相同的值(speed 的值(一遍又一遍地调用doAutoScrolling。您需要执行以下操作之一:

  • speed包装在对象中以便按引用传递
  • 使speed成为全局变量或至少在doAutoScrolling的父上下文中定义
  • setInterval替换为setTimeout并在doAutoScrolling中设置新的超时:

    var newStep = /* calculate new step */ setTimeout("doAutoScrolling("+newStep+")",1);