如何将功能与Javascript代码分开来设置Timeout

How do I separate functionality with Javascript code to set Timeout?

本文关键字:设置 Timeout 代码 Javascript 功能      更新时间:2023-09-26

我有以下代码:

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

我希望能够做这样的事情:

__this。_timeout = setTimeout(comparePanel, 3000);

如何定义和调用该函数?

p。我对JavaScript非常非常陌生,所以任何解释都是非常感谢的。

您可以像这样传递一个现有的函数给setTimeout:

// declare named function
function comparePanelTick() {
    comparePanel.removeClass(__this.CL_VISIBLE);
}

然后像你在问题中那样使用它:

__this._timeout = setTimeout(comparePanelTick, 3000);

注意:你已经有一个名为comparePanel的变量,所以使用其他东西作为函数名。

查看这个示例

<!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>

在本例中,您可以随时调用它。但是,如果你没有将setTimeout()封装在函数中,它将在初始化的那一刻被触发。

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

演示
function theTimeOutClass()
{
    this._timeout = function(){
        setTimeout(function(){
            comparePanel();
        }, 3000);
    };   
}
function comparePanel()
{
     alert('I''m comparing panels! ');
}
var toc = new theTimeOutClass();
toc._timeout();