"If at first you don't succeed; call it version 1.0" :-Unknown

Pages

Sunday, January 9, 2011

setTimeout and clearTimeout javascript Example

 setTimeout returns a value which stores a reference to the timer. The timer can then be cleared using the clearTimeout function. This is done in the following example:

<script language="Javascript">

var timeout;

function timeout_trigger() {
document.getElementById('timeout_text').innerHTML = 'The timeout has been triggered';
}

function timeout_clear() {
clearTimeout(timeout);
document.getElementById('timeout_text').innerHTML = 'The timeout has been cleared';
}

function timeout_init() {
timeout = setTimeout('timeout_trigger()', 3000);
document.getElementById('timeout_text').innerHTML = 'The timeout has been started';
}

</script>

<div>
    <input type="button" value="test timeout" onclick="timeout_init()" />
    <input type="button" value="clear timeout" onclick="timeout_clear()" />
</div>
<div id="timeout_text"></div>

When timeout_init() is called, the timeout reference is stored in the "timeout" variable. The name of the variable can be whatever you want, but it needs to be in the global scope, hence the "var timeout;" declaration at the start of the code.
Clicking the "test timeout" button starts the timer and the "clear timeout" button clears the timeout at the end
Have a nice day... 'N happy Coding :)

No comments: