同一函数中的setInterval和clearInterval

问题描述:

我有这个消息(); 功能:

function message(kind, text){   
    if(fadeOutDelay != undefined){
       clearInterval(fadeOutDelay);
    }
    $("#message").show();
    $("#message").attr('class',kind);
    $('#message').text(text);
    var fadeOutDelay = setInterval(function(){
        $("#message").fadeOut(2000);
    },10000);
}

问题是我试图清除函数重新启动时的间隔-run以防止最新消息的淡入淡出。我希望能够继续发出消息,如果它们彼此间隔10秒,则不会发生淡入淡出。基本上,如果在运行此函数时发生 setInterval ,我想取消它。

The problem is that I am trying to clear the interval when the function is re-run to prevent a fading of the latest message. I want the ability to keep making messages occur and if they are 10 seconds within each other the fade not to occur. Basically, if there is a setInterval occurring at the time this function is being run I want to cancel it.

fadeOutDelay 不在其他函数调用的范围内。您可以使用全局变量:

fadeOutDelay is not in the scope of other function calls. You could use a global variable instead:

var fadeOutDelay;
function message(kind, text){   
    if(fadeOutDelay != undefined){
       clearInterval(fadeOutDelay);
    }
    $("#message").show();
    $("#message").attr('class',kind);
    $('#message').text(text);
    fadeOutDelay = setInterval(function(){
        $("#message").fadeOut(2000);
    },10000);
}