【问题标题】:Javascript clearInterval with button clickJavascript clearInterval 与按钮单击
【发布时间】:2020-04-08 11:22:57
【问题描述】:

我在尝试将 clearInterval 绑定到按钮单击时遇到问题。此外,显然该功能是自己启动的......这是我的代码

var funky = setInterval(function() {
    alert('hello world');
}, 2000);

$('#start').click(function() {
    funky();
});
$('#stop').click(function() {
    clearInterval(funky);
});

Here's a js fiddle

【问题讨论】:

    标签: javascript jquery clearinterval


    【解决方案1】:

    你忘记添加jquery库并且分配错误,它需要在回调函数中。

    工作示例:

    var funky;
    
    $('#start').click(function() {
      funky = setInterval(function() {
        alert('hello world');
      }, 2000);
    });
    
    $('#stop').click(function() {
        clearInterval(funky);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button id="start">start</button>
    <button id="stop">stop</button>

    【讨论】:

      【解决方案2】:

      首先,是的,当您将变量分配给函数时,它会自行调用。

      其次,您的点击事件不起作用,因为您需要将时间间隔分配给点击时的变量,而不是调用函数 - 没有要调用的函数,正如您查看开发者控制台所看到的那样。

      最后,最好将 jQuery 代码包装在文档就绪函数中,以确保正确绑定所有事件处理程序。

      $(function () {
        var funky;
        $('#start').click(function() {
          funky = setInterval(function() {
            alert('hello world');
          }, 1000);
        });
      
        $('#stop').click(function() {
            clearInterval(funky);
        });
      });
      

      【讨论】:

        【解决方案3】:

        您保存了错误的值。试试这个:

        var funky = function() {
            alert('hello world');
        }
        
        var funkyId = setInterval(funky, 2000);
        
        $('#start').click(function() {
            funky();
        });
        $('#stop').click(function() {
            clearInterval(funkyId);
        });
        

        【讨论】:

        • 我认为他不想在点击开始按钮之前开始间隔
        • @Rosenumber14 - 我的读心技巧远不如我的编程技巧。也许 OP 应该阅读 How to Ask 并提出更好的问题。
        • “另外,显然这个函数是自己启动的……”
        【解决方案4】:

        这里我给你一个想法。

        1. 声明一个变量,例如let x;
        2. 创建一个要与setInterval 绑定的函数。 例如 function funky() { alert("Hello World"); }
        3. start.onclick 分配给将setInterval 分配给x 的函数。 例如start.onclick = function(){ clearInterval(x); // to prevent multiple interval if you click more than one x = setInterval(funky, 2000); // assign the setInterval to x };
        4. stop.onclick 分配给clearInterval(x) 以停止间隔。 例如stop.onclick = function() { clearInterval(x); // to stop the interval };

        就是这样。简单吧。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-06-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-06-24
          • 2021-04-07
          • 2021-09-03
          相关资源
          最近更新 更多