简体   繁体   English

如何停止setTimeout中定义的方法执行

[英]How to stop method execution defined in setTimeout

I am facing one problem in JS, please help me to resolve this.. I have two methods they are simultaneously executing one after other.. I have to stop them after second click on image. 我在JS中遇到一个问题,请帮助我解决这个问题。.我有两种方法同时一个接一个地执行。.在第二次单击图像后,我必须停止它们。 Below is my JS code 下面是我的JS代码

I am calling fadeIn(img1, img2, img3) after first click on image then some animation will be goes on, once I click second time the whole animation(method execution) should be stopped. 第一次单击图像后,我将调用fadeIn(img1,img2,img3),然后将继续播放某些动画,一旦我第二次单击,应停止整个动画(方法执行)。

var t1 = 0;
var t2 = 0;
function fadeIn(img1, img2, img3) {
$(imgIdForClick_1).addClass('animated pulse');
$('#cashBar1').addClass('animated pulse');
$('#cashBarDec1').addClass('animated pulse');

var t1 = setTimeout(function() {
    fadeOut(img1, img2, img3);
    if (clickCount_1 >= 2) {
        alert("clicked 1");
        return false;
    }
 }, 500);

 //t1 = setTimeout(fadeOut, 500);
};
function fadeOut(img11, img22, img33) {
$(imgIdForClick_1).removeClass('animated pulse');
$('#cashBar1').removeClass('animated pulse');
$('#cashBarDec1').removeClass('animated pulse');
var t2 = setTimeout(function() {
    fadeIn(img11, img22, img33);
    if (clickCount_1 >= 2) {
        alert("clicked 2");
        return false;
    } 
}, 500);

//t2 = setTimeout(fadeIn, 500);
};

By below code I am calling this snippet in first click 通过下面的代码,我在第一次点击时将此代码段称为

imgId1 = $('#img1');
        imgId2 = $('#cashBar1');
        imgId3 = $('#cashBarDec1');
        fadeIn(imgId1, imgId2, imgId3); 

After second click clickCount_1 varibale will be 2 第二次单击后,clickCount_1变量将为2

clearTimeout(t1);
    clearTimeout(t2);

See the DEMO . 参见演示 Click on the image to stop animation. 单击图像以停止动画。 I have added a flag that would be checked upon the call of the function, and if the value is true then and then only the functions would be called. 我添加了一个flag ,该flag将在调用函数时进行检查,如果该值为true ,则仅会调用这些函数。 The flag would be set to false when clicked on image, so the function would be called no longer. 单击图像时,该flag将设置为false ,因此将不再调用该函数。

code: 码:

var animate = true;
function fadeIn() {
    $('#pulseDiv').find('div#advisersDiv').delay(400).addClass("pulse");
    if(animate == true)
    {        
        setTimeout(fadeOut,1000);
    }
};

function fadeOut() {
    $('#pulseDiv').find('div#advisersDiv').delay(400).removeClass("pulse");
    if(animate == true)
    {
        setTimeout(fadeIn,1000);
    }    
};
fadeIn();

$('#image').click(function(){
    animate = false;
    alert('now the animation will stop');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM