Justin808 Justin808 - 2 years ago 210
Javascript Question

Can a setInterval function stop itself?

I have a jsFiddle up with an example to work from.

$().ready(function() {
$('.test').each(function() {
$this = $(this);
$this.data('Worker', function() {
$('#stop').html((parseInt($('#stop').html()) + 1))
setInterval($this.data('Worker'), 100);

$('#stop').click(function() {
// I want the worker function to stop being triggered here

What I would like to do is attach a worker function to an element in the DOM so that when the element is removed, the worker function stops.

Is something like this possible?

Answer Source

Here you go:

var stopBtn = $( '#stop' );

$( '.test' ).each(function ( i, elem ) {
    var tid = setInterval(function () {
        if ( elem.parentNode ) {
            stopBtn.html(function ( i, num ) { return parseInt(num,10) + 1; });
        } else {
            clearInterval( tid );
    }, 1000);

stopBtn.click(function () {
    $( '.test' ).remove();


First of all we need a closure - the interval function needs to know which test-DIV is its "owner", ergo, we need to pass a reference to the DIV into the interval function. In my code, that reference is stored in the elem variable, which is available inside the interval function because of closure. So, the interval function checks whether or not its "owner" DIV is still attached to the DOM (by examining its parent node). If it is, the stop-button is incremented. If it's not, the interval is cleared. However, in order to be able to clear the interval, we require its timer ID. We have this ID, because we stored it inside the "tid" variable (the setInterval call returns the timer ID).

Live demo: http://jsfiddle.net/simevidas/ZjY7k/15/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download