jjzjj

javascript - JavaScript 中奇怪的计时行为

coder 2025-01-11 原文

我在尝试实现动态滚动(这不是个好主意不是问题)并遇到了一些“奇怪”的行为。

function scroll(timestamp){
    var deltaTime = timestamp - this.scrollLastTime;
    this.scrollLastTime = timestamp;
    console.log(deltaTime);
    var newPosition = this.scrollTop + this.scrollSpeed*deltaTime;
    if(newPosition <= 0){
      this.scrollTop = 0;
      this.scrolling = false;
      return;
    }else if(newPosition > this.scrollHeight-this.clientHeight){
      this.scrollTop = this.scrollHeight-this.clientHeight;
      this.scrolling = false;
    }else{
      this.scrollTop = newPosition;
      var newSpeed = this.scrollSpeed + Math.sign(this.scrollSpeed) * this.scrollAcceleration*deltaTime;
      if(this.scrollSpeed < 0 && newSpeed >= 0){
        this.scrolling = false;
      }else if(this.scrollSpeed >0 && newSpeed <= 0){
        this.scrolling = false;
      }else{
        this.scrollSpeed = newSpeed;
        window.requestAnimationFrame(this.scrollCallback);
      }
    }
  }
  document.getElementById("0").addEventListener('wheel',
        function(e){
            this.scrollSpeed = e.wheelDelta/100;
            if(!this.scrolling){
              this.scrolling = true;
              this.scrollLastTime = performance.now();
              this.scrollAcceleration = -0.01;
              if(!this.scrollCallback)this.scrollCallback = scroll.bind(this);
              window.requestAnimationFrame(this.scrollCallback);
            }
            e.preventDefault();
        });

问题是 deltaTime 经常变成负数,我错过了什么?

编辑:如果有帮助,我正在使用 Chromium 版本 51.0.2704.79 Ubuntu 14.04(64 位)。

最佳答案

正如@Whothehellisthat 已经在他的评论中指出的那样:

the rAF timestamp isn't very reliable

这里有一个小例子来证明:

document.getElementById("button").addEventListener('click', function(e){
        this.valueOfPerformanceNow = performance.now();
        if(!this.clickCallback)this.clickCallback = printTime.bind(this);
        window.requestAnimationFrame(this.clickCallback);
});

function printTime(timestamp){
  $("#perfromanceNow").val(this.valueOfPerformanceNow);
  $("#delta").val(timestamp-this.valueOfPerformanceNow);
  $("#timestamp").val(timestamp);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type="submit" id="button" value="print current time"><br>
  <label>performance.now():</label>
  <input type="text" id="perfromanceNow" readonly><br>
  <label>timestamp:</label>
  <input type="text" id="timestamp" readonly><br>
   <label>delta:</label>
  <input type="text" id="delta" readonly>
<div>

有一个简单的解决方法。您可以在方法的开头使用 var timestamp = performance.now(); 而不是通过 rAF 时间获取时间戳。

这是一个工作示例:

document.getElementById("button").addEventListener('click', function(e){
        this.valueOfPerformanceNow = performance.now();
        if(!this.clickCallback)this.clickCallback = printTime.bind(this);
        window.requestAnimationFrame(this.clickCallback);
});

function printTime(){
  var timestamp = performance.now();
  $("#perfromanceNow").val(this.valueOfPerformanceNow);
  $("#delta").val(timestamp-this.valueOfPerformanceNow);
  $("#timestamp").val(timestamp);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type="submit" id="button" value="print current time with new timestamp initialization"><br>
  <label>performance.now():</label>
  <input type="text" id="perfromanceNow" readonly><br>
  <label>timestamp:</label>
  <input type="text" id="timestamp" readonly><br>
   <label>delta:</label>
  <input type="text" id="delta" readonly>
<div>

关于javascript - JavaScript 中奇怪的计时行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38848628/

有关javascript - JavaScript 中奇怪的计时行为的更多相关文章

  1. ruby - 如何根据特征实现 FactoryGirl 的条件行为 - 2

    我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden

  2. ruby - Ruby gsub 替换中的行为不一致? - 2

    两个gsub产生不同的结果。谁能解释一下为什么?代码也可在https://gist.github.com/franklsf95/6c0f8938f28706b5644d获得.ver=9999str="\tCFBundleDevelopmentRegion\n\ten\n\tCFBundleVersion\n\t0.1.190\n\tAppID\n\t000000000000000"putsstr.gsub/(CFBundleVersion\n\t.*\.).*()/,"#{$1}#{ver}#{$2}"puts'--------'putsstr.gsub/(CFBundleVersio

  3. ruby-on-rails - Ruby 中意外的大小写行为 - 2

    我在一段非常简单的代码(如我所想)中得到了一个错误的值:org=4caseorgwhenorg=4val='H'endputsval=>nil请不要生气,我希望我错过了一些非常明显的东西,但我真的想不通。谢谢。 最佳答案 这是典型的Ruby错误。case有两种被调用的方法,一种是你传递一个东西作为分支的基础,另一种是你不传递的东西。如果您确实在case中指定了一个表达式语句然后评估所有其他条件并与===进行比较.在这种情况下org评估为false和org===false显然不是真的。所有其他情况也是如此,它们要么是真的,要么是假的。

  4. ruby - 使对象的行为类似于 ruby​​ 中并行分配的数组 - 2

    假设您在Ruby中执行此操作:ar=[1,2]x,y=ar然后,x==1和y==2。是否有一种方法可以在我自己的类中定义,从而产生相同的效果?例如rb=AllYourCode.newx,y=rb到目前为止,对于这样的赋值,我所能做的就是使x==rb和y=nil。Python有这样一个特性:>>>classFoo:...def__iter__(self):...returniter([1,2])...>>>x,y=Foo()>>>x1>>>y2 最佳答案 是的。定义#to_ary。这将使您的对象被视为要分配的数组。irb>o=Obje

  5. ruby-on-rails - 使用 javascript 更改数据方法不会更改 ajax 调用用户的什么方法? - 2

    我遇到了一个非常奇怪的问题,我很难解决。在我看来,我有一个与data-remote="true"和data-method="delete"的链接。当我单击该链接时,我可以看到对我的Rails服务器的DELETE请求。返回的JS代码会更改此链接的属性,其中包括href和data-method。再次单击此链接后,我的服务器收到了对新href的请求,但使用的是旧的data-method,即使我已将其从DELETE到POST(它仍然发送一个DELETE请求)。但是,如果我刷新页面,HTML与"new"HTML相同(随返回的JS发生变化),但它实际上发送了正确的请求类型。这就是这个问题令我困惑的

  6. ruby - 了解在 Ruby 中与 lambda 一起使用的 inject 行为 - 2

    我经常将预配置的lambda插入可枚举的方法中,例如“map”、“select”等。但是“注入(inject)”的行为似乎有所不同。例如与mult4=lambda{|item|item*4}然后(5..10).map&mult4给我[20,24,28,32,36,40]但是,如果我制作一个2参数lambda用于像这样的注入(inject),multL=lambda{|product,n|product*n}我想说(5..10).inject(2)&multL因为“inject”有一个可选的单个初始值参数,但这给了我......irb(main):027:0>(5..10).inject

  7. ruby - Ruby 性能中的计时器 - 2

    我正在寻找一个用ruby​​演示计时器的在线示例,并发现了下面的代码。它按预期工作,但这个简单的程序使用30Mo内存(如Windows任务管理器中所示)和太多CPU有意义吗?非常感谢deftime_blockstart_time=Time.nowThread.new{yield}Time.now-start_timeenddefrepeat_every(seconds)whiletruedotime_spent=time_block{yield}#Tohandle-vesleepinteravalsleep(seconds-time_spent)iftime_spent

  8. ruby - 在 Mechanize 中使用 JavaScript 单击链接 - 2

    我有这个:AccountSummary我想单击该链接,但在使用link_to时出现错误。我试过:bot.click(page.link_with(:href=>/menu_home/))bot.click(page.link_with(:class=>'top_level_active'))bot.click(page.link_with(:href=>/AccountSummary/))我得到的错误是:NoMethodError:nil:NilClass的未定义方法“[]” 最佳答案 那是一个javascript链接。Mechan

  9. ruby - 奇怪的 ruby​​ for 循环行为(为什么这样做有效) - 2

    defreverse(ary)result=[]forresult[0,0]inaryendresultendassert_equal["baz","bar","foo"],reverse(["foo","bar","baz"])这行得通,我想了解原因。有什么解释吗? 最佳答案 如果我使用each而不是for/in重写它,它看起来像这样:defreverse(ary)result=[]#forresult[0,0]inaryary.eachdo|item|result[0,0]=itemendresultendforainb基本上就

  10. ruby - 比较 rspec 中的 float 时的奇怪行为 - 2

    以下测试中的第3个失败:specify{(0.6*2).shouldeql(1.2)}specify{(0.3*3).shouldeql(0.3*3)}specify{(0.3*3).shouldeql(0.9)}#thisonefails这是为什么呢?这是浮点问题还是ruby​​或rspec问题? 最佳答案 从rspec-2.1开始specify{(0.6*2).shouldbe_within(0.01).of(1.2)}在那之前:specify{(0.6*2).shouldbe_close(1.2,0.01)}

随机推荐