【问题标题】:Clear timeout at start of function [duplicate]在函数开始时清除超时[重复]
【发布时间】:2014-08-20 22:51:37
【问题描述】:

http://jsfiddle.net/yhXum/4/

当你按下开始时,盒子会每两秒移动到一个新位置,但如果你一直按下按钮,则:

setTimeout("random()", 2000);

会堆积起来让盒子疯狂地移动。

如何让它在每次调用函数时重置?

这是一个重复问题的原因是因为我刚刚开始学习,我真的需要有人为我做这件事,因为我真的不知道如何实现类似问题的答案。

【问题讨论】:

  • 使用setTimeout(random, 2000) 而不是setTimeout("random()", 2000) 通常被认为是一种好的做法。

标签: javascript settimeout


【解决方案1】:

您始终可以使用 clearTimeout。但是,我的建议是隐藏开始按钮。如果您实际上是将其放入网站,那么这对您的用户也会更有意义。

http://jsfiddle.net/prankol57/g3heA/

对于停止按钮,您可以使用名为 interval 的变量来跟踪间隔 id 并稍后将其清除。

function start() {
    // Hide the start button
    document.querySelector("#start").style.display = "none";
    document.querySelector("#stop").style.display = "block";
    random();
}

function stop() {
    clearTimeout(interval);
    document.querySelector("#stop").style.display = "none";
    document.querySelector("#start").style.display = "block";
}

【讨论】:

    【解决方案2】:

    使用clearTimeout:

    var myTimeout;
    function random()
    {
        clearTimeout(myTimeout);
        x = Math.floor(Math.random() * (10 - 0 + 1)) + 0;
        x = (x * 10);
        y = Math.floor(Math.random() * (10 - 0 + 1)) + 0;
        y = (y * 10);
    
        document.getElementById("box").style.left = x + "px";
        document.getElementById("box").style.top = y + "px";
    
        myTimeout = setTimeout("random()", 2000);    
    }
    

    http://jsfiddle.net/yhXum/5/

    【讨论】:

      【解决方案3】:

      检查这个 fiddle link 没有超时

      var flag=true;
      function random()
      {
      x = Math.floor(Math.random() * (10 - 0 + 1)) + 0;
      x = (x * 10);
      y = Math.floor(Math.random() * (10 - 0 + 1)) + 0;
      y = (y * 10);
      
      document.getElementById("box").style.left = x + "px";
      document.getElementById("box").style.top = y + "px";
          if(flag){
              setTimeout(random, 2000);
              flag=false;
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 2018-04-13
        • 1970-01-01
        • 2015-06-21
        • 2015-07-04
        • 1970-01-01
        • 2011-07-19
        • 2019-12-03
        • 2023-03-03
        • 1970-01-01
        相关资源
        最近更新 更多