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?
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.
The JavaScript setInterval() method returns an ID which can be used by the clearInterval() method to stop the interval.
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() .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With