如何使用Javascript代码分离功能以设置超时?

如何使用Javascript代码分离功能以设置超时?,javascript,jquery,Javascript,Jquery,我有以下代码: var comparePanel = $(__this.NOTICE_BODY); clearTimeout(__this._timeout); comparePanel.addClass(__this.VISIBLE); __this._timeout = setTimeout(function () { comparePanel.removeClass(__this.CL_VISIBLE);

我有以下代码:

var comparePanel = $(__this.NOTICE_BODY);
        clearTimeout(__this._timeout);
        comparePanel.addClass(__this.VISIBLE);
        __this._timeout = setTimeout(function () {
            comparePanel.removeClass(__this.CL_VISIBLE);
        }, 3000); 
    }
})
以下内容重复了几次:

__this._timeout = setTimeout(function () {
            comparePanel.removeClass(__this.CL_VISIBLE);
        }, 3000);
我希望能够做到以下几点:

// declare named function
function comparePanelTick() {
    comparePanel.removeClass(__this.CL_VISIBLE);
}
__此._timeout=setTimeout(comparePanel,3000)

如何定义和调用该函数?

另外,我对JavaScript非常陌生,因此非常感谢您对所发生的一切进行解释。

请参阅此示例

<!DOCTYPE html>
<html>
<body>

<p>Click the first button alert "Hello" after waiting 3 seconds.</p>
<p>Click the second button to prevent the first function to execute. (You must click it     before the 3 seconds are up.)</p>

<button onclick="myFunction()">Try it</button>
<button onclick="myStopFunction()">Stop the alert</button>

<script>
var myVar;

function myFunction() {
    myVar = setTimeout(function(){alert("Hello")}, 3000);
}

function myStopFunction() {
    clearTimeout(myVar);
}
</script>

</body>
</html>

等待3秒钟后,单击第一个按钮警报“Hello”

单击第二个按钮以阻止执行第一个函数。(您必须在3秒钟结束前单击它。)

试试看 停止警报 var-myVar; 函数myFunction(){ myVar=setTimeout(函数(){alert(“Hello”)},3000); } 函数myStopFunction(){ 清除超时(myVar); }
您可以将现有函数传递给
setTimeout
,如下所示:

// declare named function
function comparePanelTick() {
    comparePanel.removeClass(__this.CL_VISIBLE);
}
然后像你在问题中所展示的那样使用它:

__this._timeout = setTimeout(comparePanelTick, 3000);

注意:您已经有一个名为
comparePanel
的变量,因此请使用其他变量作为函数名。

在本例中,您可以随时调用它。但是,如果您不将setTimeout()包装到函数中,它将在初始化后立即启动

this._timeout = setTimeout(function(){
            comparePanel();
        }, 3000);


不过,该函数可能应该命名为其他名称。因为在OP发布的代码中,
comparePanel
已经绑定到
$(\uu this.NOTICE\u BODY)
。看起来不错!顺便问一下,您知道什么是comparePanel.removeClass(this.CL\u可见);这对您来说意味着什么,以及为什么这在这个上下文中可能很重要?
\u这个
在父范围中可用,因此不需要其他上下文。我假设它隐藏并显示了一个元素。