santa
santa

Reputation: 12512

Reset counter for function repeats

I have a function that checks if certain element has an attribute and if it is not found the function runs again. It does it until the attribute is found or the maximum number of times this functions is allowed to call itself is reached.

var cnt = 0;

function myFunction() {
    if (!$('.myEm').is('[style]') && cnt < 10) {
            setTimeout(function () {
                myFunction();
                cnt++;
        }, 3000);
    }
}

myFunction();

However, if user selects an option in another element (myDropDown) the counter for the original function needs to be reset to zero and myDropDown needs to start running again.

$(document).on('change', '#myDropDown', function() {
    var cnt = 0;
    myFunction();
});

I'm struggling to reset this counter value. I put together a FIDDLE to show what I'm trying to accomplish.

Upvotes: 1

Views: 1736

Answers (3)

Andr&#233; Caetano
Andr&#233; Caetano

Reputation: 23

you are defining the cnt as local inside the change handleR you need to use the global variable. just remove var inside change handler

Upvotes: 0

Captain Nova
Captain Nova

Reputation: 31

The loop will keep running so you shouldn't need to call that again, just use the jQuery change function:

$('#myDropDown').change(function () {
    cnt = 0;
});

edit: just realized that the timer stops at 10, so updated the JSFiddle to restart the timer loop if it has reached 10.

See updated JSFiddle here: http://jsfiddle.net/91on7c1f/

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337590

You need to store the reference to the timer in a variable, then call clearTimeout() on change of the select element. You also should remove the var statement before you reset cnt back to 0, otherwise you will change its scope. Try this:

$(document).on('change', '#myDropDown', function () {
    clearTimeout(timer);
    cnt = 0;
    myFunction();
});

Update fiddle

Upvotes: 2

Related Questions