GIVE-ME-CHICKEN
GIVE-ME-CHICKEN

Reputation: 1269

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

I have the following code:

var comparePanel = $(__this.NOTICE_BODY);
        clearTimeout(__this._timeout);
        comparePanel.addClass(__this.VISIBLE);
        __this._timeout = setTimeout(function () {
            comparePanel.removeClass(__this.CL_VISIBLE);
        }, 3000); 
    }
})

The following has been repeated a few times:

__this._timeout = setTimeout(function () {
            comparePanel.removeClass(__this.CL_VISIBLE);
        }, 3000);

I want to be able to do something like this:

__this._timeout = setTimeout(comparePanel, 3000);

How do I define and call that function?

PS. I am very very new to JavaScript so any explanation of what is going on is greatly appreciated.

Upvotes: 1

Views: 71

Answers (3)

kockburn
kockburn

Reputation: 17626

In this example, you can call it any time you want. However if you don't wrap your setTimeout() in a function, it'll be fired the second it gets initialized.

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

DEMO

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

Upvotes: 0

MrCode
MrCode

Reputation: 64536

You can pass an existing function to setTimeout like this:

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

Then use it like you show in the question:

__this._timeout = setTimeout(comparePanelTick, 3000);

Note: you already have a variable named comparePanel so use something else for the function name.

Upvotes: 2

R D
R D

Reputation: 1332

See this sample

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

Upvotes: 1

Related Questions