Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/428.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何停止js setInterval_Javascript_Jquery - Fatal编程技术网

Javascript 如何停止js setInterval

Javascript 如何停止js setInterval,javascript,jquery,Javascript,Jquery,我写了一个函数,根据间隔每1秒更改一次css背景图像,它工作正常,问题是现在我想停止切换背景图像的函数,间隔设置一直覆盖我 我的代码: var backgrounds = new Array( 'url(/srv/admin/img/announcement/envelope_blue.png)' , 'url(/srv/admin/img/announcement/envelope_red.png)' ); var current = 0; function nextBackgrou

我写了一个函数,根据间隔每1秒更改一次css背景图像,它工作正常,问题是现在我想停止切换背景图像的函数,间隔设置一直覆盖我

我的代码:

  var backgrounds = new Array(
'url(/srv/admin/img/announcement/envelope_blue.png)'
, 'url(/srv/admin/img/announcement/envelope_red.png)'

);

var current = 0;

function nextBackground() {   
    current++;
    current = current % backgrounds.length;
    jQuery("#open_msg_tlbr_img").css('background-image', backgrounds[current]);
    jQuery("#open_msg_tlbr_img").css('width','35px');
    jQuery("#open_msg_tlbr_img").css('height','35px');


}
setInterval(nextBackground, 1000);

jQuery("#open_msg_tlbr_img").css('background-image', backgrounds[0]);    
我尝试使用:clearInterval()


如何阻止此怪物?

您正在分配
setInterval
返回的对象,以便以后可以清除它,将
setInterval
返回的对象传递到
clearInterval
函数中进行清除。注意,您需要在多个函数中使用全局变量

分配由
setInterval返回的对象

intr = setInterval(nextBackground, 1000);
clearInterval(intr );
将setInterval引用对象传递给
clearInterval

intr = setInterval(nextBackground, 1000);
clearInterval(intr );

使用变量保存
setInterval
的返回值,然后将其清除:

var interval = setInterval(nextBackground, 1000);
clearInterval(interval);
setInterval()
返回一个区间ID,您可以将其传递给
clearInterval()


在提出此类问题之前,请先查阅有关您正在使用的函数的文档。有一个指向的链接。