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

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

问题描述

我试图暂停然后播放setInterval循环.

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?

推荐答案

出现此特定问题的原因:

JSFiddle将代码包装在一个函数中,因此 start()不在全局范围内定义.

The reason you're seeing this specific problem:

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

故事的寓意:不要使用内联事件绑定.使用 addEventListener /attachEvent.

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

请不要将字符串传递给setTimeoutsetInterval. eval变相.

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

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

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天全站免登陆