Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/76.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 每2秒运行一次函数,直到变量发生变化_Javascript_Jquery - Fatal编程技术网

Javascript 每2秒运行一次函数,直到变量发生变化

Javascript 每2秒运行一次函数,直到变量发生变化,javascript,jquery,Javascript,Jquery,如何使interval函数在图像长度大于0时停止运行 我的代码 var theImages = $('.awesome-slider .slides img'); function checkImages(){ theImages = $('.awesome-slider .slider img'); // other stuff happens here but only want it to run once } if(theImages.length == 0){

如何使interval函数在图像长度大于0时停止运行

我的代码

var theImages = $('.awesome-slider .slides img');

function checkImages(){
    theImages = $('.awesome-slider .slider img');
    // other stuff happens here but only want it to run once
}

if(theImages.length == 0){
    window.setInterval(function (){
            checkImages();
    })
}
图像长度最终会变为大于0,但为什么间隔函数会继续运行?

使用
clearInterval()


使用window.setTimeout代替interval

根据定义,如果不显式关闭interval,它将继续运行。
您需要setTimeout,它只运行一次。在图像长度测试之后,如果需要,您可以创建另一个实例

我建议您使用
setTimeout
而不是
setInterval

var theImages=$('.awesome slider.slides img');
函数checkImages(){
如果(图像长度!==0){
setTimeout(函数(){
检查图像();
}, 2000);
}
}

检查图像()这不是正确的代码,请检查并正确发布。“为什么间隔函数一直运行?”因为您从未取消它。。。你永远不会说让它停止,这样它就会继续运行。这里不需要
clearTimeout
,条件应该是opposite@AlexK Dude,
setTimeout
是比
setInterval
更简单的解决方案。你应该考虑使用它。这也持续运行:/@ Alxik将它改为<代码>(IIIGITES!长度=0){< /代码> >
let interval = window.setInterval(function () {

                 checkImages();

                 if (theImages.length == 0) {
                   clearInterval(interval);
                 };

               }, 2000);