Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a setInterval function stop itself?

Tags:

jquery

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
        $('.test').remove();
    });
});

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?

like image 474
Justin808 Avatar asked Apr 22 '11 23:04

Justin808


People also ask

Does setInterval stop?

The setInterval() method calls a function at specified intervals (in milliseconds). The setInterval() method continues calling the function until clearInterval() is called, or the window is closed.

Which function will stop the continuation of setInterval function?

The JavaScript setInterval() method returns an ID which can be used by the clearInterval() method to stop the interval.

How does the setInterval () function work in?

setInterval() The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval() .

How do you stop setInterval calls?

Answer: Use the clearInterval() Method The setInterval() method returns an interval ID which uniquely identifies the interval. You can pass this interval ID to the global clearInterval() method to cancel or stop setInterval() call.


1 Answers

Late to the party, but I solved this way:

var id = setInterval(function()
{
    if(some_condition)
    {
        clearInterval(id);
    }
}, 1000);

Definitely the simplest way out of all: no unnecessary storing, no tricks.

like image 100
Andrius Naruševičius Avatar answered Sep 19 '22 20:09

Andrius Naruševičius