如何开始和停止/暂停 setInterval? [英] How to start and stop/pause setInterval?

查看:55
本文介绍了如何开始和停止/暂停 setInterval?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试暂停,然后播放 setInterval 循环.

在我停止循环后,/attachEvent.


其他注意事项:

不要将字符串传递给 setTimeoutsetInterval.它是伪装的 eval.

改用函数,并使用 var 和空格:

var input = document.getElementById("input"),添加;函数开始(){添加 = setInterval(function() {输入值++;}, 1000);}start();

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><input type="number" id="input"/><input type="button" onclick="clearInterval(add)" value="stop"/><input type="button" onclick="start()" value="start"/>

I'm trying to pause and then play a setInterval loop.

After I have stopped the loop, the "start" button in my attempt doesn't seem to work :

input = document.getElementById("input");

function start() {
  add = setInterval("input.value++", 1000);
}
start();

<input type="number" id="input" />
<input type="button" onclick="clearInterval(add)" value="stop" />
<input type="button" onclick="start()" value="start" />

Is there a working way to do this?

解决方案

The reason you're seeing this specific problem:

JSFiddle wraps your code in a function, so start() is not defined in the global scope.


Moral of the story: don't use inline event bindings. Use addEventListener/attachEvent.


Other notes:

Please don't pass strings to setTimeout and setInterval. It's eval in disguise.

Use a function instead, and get cozy with var and white space:

var input = document.getElementById("input"),
  add;

function start() {
  add = setInterval(function() {
    input.value++;
  }, 1000);
}

start();

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="input" />
<input type="button" onclick="clearInterval(add)" value="stop" />
<input type="button" onclick="start()" value="start" />

这篇关于如何开始和停止/暂停 setInterval?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆