Javascript setInterval clearInterval简单示例不工作解释? [英] Javascript setInterval clearInterval Simple Example Not Working Explained?

查看:200
本文介绍了Javascript setInterval clearInterval简单示例不工作解释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的JS setInterval和clearInterval示例,它不起作用。必须有一个潜在的原因,为什么它不起作用,我想知道为什么:

I have a very simple JS setInterval and clearInterval example that doesn't work. There has got to be an underlying reason why it does not work and I would like to know why that is:

 var automessage;

 function turnON() //executed by onclick event A
 {
   var automessage = setInterval(function(){ something() }, 2000);
 }

 function turnOff() //executed by onclick event B
 {
   clearInterval(automessage);
 }

 function something()
 {
   //pulls instant messages
 }

在此示例中,最终用户单击按钮以启动定时间隔过程,单击另一个按钮以停止定时间隔过程,然后再次单击打开按钮再次开始这个过程。从本质上讲,它将是一个开/关风格的过程。

In this example, an end-user clicks a button to start a timed interval process, clicks another button to stop the timed interval process, and then clicks the on button again to start the process again. Essentially, it would be an on/off styled process.

这不起作用,我试图找出原因。我可以使Stackoverflow上提供的所有其他数百个示例都可以工作,但我真的需要一个开/关样式的进程,不仅限于on,然后off。 setInterval应该可以随时打开和关闭。

This doesn't work and I am trying to figure out why. I can make all of the hundreds of other examples offered on Stackoverflow to work, but I really need an on/off styled process that isn't limited to just on, and then off. The setInterval should be able to turn on and off at any time.

我非常感谢任何人的帮助。另外,我不使用任何Jquery库。

I really appreciate anyone's help. Also, I do not use any Jquery libraries.

推荐答案

automessage 是声明两次 - 作为全局变量和局部变量。尝试:

automessage is declared twice - as a global variable and as a local variable. try:

function turnON() //executed by onclick event A
{
    automessage = setInterval(function(){ something() }, 2000);
}

这篇关于Javascript setInterval clearInterval简单示例不工作解释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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