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

How to stop method execution defined in setTimeout

本文关键字:方法 执行 定义 何停止 setTimeout      更新时间:2023-09-26

我在JS中面临一个问题,请帮助我解决这个问题。我有两个方法,它们一个接一个地同时执行。我必须在第二次点击图像后阻止他们。下面是我的JS代码

我在第一次点击图像后调用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);
};

通过下面的代码,我在第一次点击

时调用这个代码片段
imgId1 = $('#img1');
        imgId2 = $('#cashBar1');
        imgId3 = $('#cashBarDec1');
        fadeIn(imgId1, imgId2, imgId3); 

第二次点击后变量clickCount_1将为2

clearTimeout(t1);
    clearTimeout(t2);

参见演示。点击图像停止动画。我添加了一个flag,它将在函数调用时进行检查,如果值是true,那么只有函数才会被调用。当点击图像时,flag将被设置为false,因此将不再调用该函数。

代码:

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');
});