Javascript 我怎样才能停止这种闪烁效果?

Javascript 我怎样才能停止这种闪烁效果?,javascript,Javascript,我有一个Javascript函数,它通过替换按钮图像来循环创建闪烁效果 function blinkit() { intrvl = 0; for (nTimes = 0; nTimes < 500; nTimes++) { intrvl += 1000; t = setTimeout("document.getElementById('imgshowreport').src='report_icon.png';",intrvl); intr

我有一个Javascript函数,它通过替换按钮图像来循环创建闪烁效果

function blinkit() {
   intrvl = 0;
   for (nTimes = 0; nTimes < 500; nTimes++)  {
      intrvl += 1000;
      t = setTimeout("document.getElementById('imgshowreport').src='report_icon.png';",intrvl);
      intrvl += 1000;
      t = setTimeout("document.getElementById('imgshowreport').src='report_icon2.png';",intrvl);
   }
}
函数blinkit(){
intrvl=0;
用于(nTimes=0;nTimes<500;nTimes++){
intrvl+=1000;
t=setTimeout(“document.getElementById('imgshowreport').src='report_icon.png';”,intrvl);
intrvl+=1000;
t=setTimeout(“document.getElementById('imgshowreport').src='report_icon2.png';”,intrvl);
}
}
这可以达到目的,但当点击按钮时,我希望停止闪烁。如何在不刷新整个页面的情况下执行此操作?

尝试中断
您可以使用中断语法

break


使用
break
终止循环是无用的,因为在用户单击按钮之前,您的循环已经结束并设置了所有超时

最好使用
setInterval
一次,而不是排队等待数百个单独的超时。然后你就可以一举结束间歇

也不应使用字符串代码,而应使用函数:

var myInterval = null;

function blinkit() {
  var i = 0;
  myInterval = setInterval(function() {
     document.getElementById('imgshowreport').src = (i % 2) ? 'report_icon2.png' : 'report_icon.png';
     i++;
  }, 1000);
}

document.getElementById('imgshowreport').onclick = function() {
   if (myInterval != null) {
      clearInterval(myInterval);
      myInterval = null;
      document.getElementById('imgshowreport').src = 'report_icon.png';
   }
};

我没有测试过它的打字错误,但基本逻辑是正确的。

这根本不是一个完整或有用的答案。该网站有什么问题,为什么这不是一个有用的答案,因为“break”是这个问题唯一优雅的答案?(a)你为什么不点击我提供的链接,它会把你带到一个大型网站,列出所有的原因?(b) 实际上,
break
根本不能解决这个问题。他问如何停止循环。我想他有办法检查什么时候停下来,他在问怎么停。我提供的链接是一些代码示例,说明了break的用法;陈述它不涉及认证、商标问题等。您根本就没有阅读问题正文吗?商标和它有什么关系?简单的事实是,这个答案并不能回答眼前的问题。也许你可以告诉他在哪里休息。你的回答根本没有提到按钮点击。@Kingpin:这没有帮助。这个问题的问题是你在假设如何停止闪烁,假设你必须“停止javascript循环”。事实上,停止循环是没有用的,因为你的问题的整个部分都是在转移注意力。下次请描述你的目标,而不是你认为解决方案应该是什么。你的
函数blinkit()
很快就完成了,没有中断:你生成了1000个setTimeout。上次超时在500*1000毫秒(8分20秒)后完成。请参阅Tomalak Geret'kal的答案以了解实现变量。
var myInterval = null;

function blinkit() {
  var i = 0;
  myInterval = setInterval(function() {
     document.getElementById('imgshowreport').src = (i % 2) ? 'report_icon2.png' : 'report_icon.png';
     i++;
  }, 1000);
}

document.getElementById('imgshowreport').onclick = function() {
   if (myInterval != null) {
      clearInterval(myInterval);
      myInterval = null;
      document.getElementById('imgshowreport').src = 'report_icon.png';
   }
};