同一函数中的setInterval和clearInterval [英] setInterval and clearInterval within same function

查看:117
本文介绍了同一函数中的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);
}

这篇关于同一函数中的setInterval和clearInterval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆