No puedo hacer que setInterval () funcione en Javascript

i have an algorithm that generates permutations of a given word. I'm trying to use setInterval() to generate the next permutation but the function runs only once! I can't figure out why. I don't get any error messages. Here is my code

var splitted;
var t;
 $(document).ready(function() {
$('#SubmitBtn').click(function() {
    //change Start to Stop and change button id
    $('#SubmitBtn').attr('id','StopBtn').attr('value','Stop');
    //and add click event to it
    $('#StopBtn').click(function() {
        clearInterval(t);
        $('#StopBtn').attr('value','Submit');
        $('StopBtn').attr('id','SubmitBtn');
    });
    if ($('#AnagramTxtArea').val().length>0)
            $('#AnagramTxtArea').text('');
    var inputTxt = $('#anagram').val();
    splitted = inputTxt.split("");
    splitted.sort(); //first sort the array in order to generate permutations
    $('#AnagramTxtArea').append(splitted.join("") + " ");
    t= setInterval(GeneratePermutation(),10);
});
 });

 var AnagramObj = new Anagram();
 function GeneratePermutation() {
        splitted = AnagramObj.NextPermutation(splitted);
        if (splitted!=null)
            $('#AnagramTxtArea').append(splitted.join("") + " ");       
        else  
            $('#StopBtn').click();

    }

y HTML:

<div id="content">
<input id="anagram" type="text" placeholder="Insert your text here" maxlength="80"/>                    <br />
<input id="SubmitBtn" type="submit" value="submit" />
<br />
<textarea id="AnagramTxtArea" readonly="readonly"></textarea>

</div> 

EDIT: Yet, another problem:

When calling $('#StopBtn').click() code continues to execute after existing the click event function. So i'm in an infinite loop.

preguntado el 27 de agosto de 11 a las 18:08

3 Respuestas

You need to pass the function object itself to setInterval(), not the result of a call to the function:

t = setInterval(GeneratePermutation,10);
                                // ^ No parentheses

EDIT: On your second question, what you can do is check whether the interval is running. If it is, then cancel it:

var splitted;
var t;
$(document).ready(function() {
$('#SubmitBtn').click(function() {
    if (t !== undefined) { //interval is already running
        clearInterval(t);
        t = undefined;
        $('#SubmitBtn').attr('value','Submit');
    } else {
        //change Start to Stop
        $('#SubmitBtn').attr('value','Stop');
        if ($('#AnagramTxtArea').val().length>0)
                $('#AnagramTxtArea').text('');
        var inputTxt = $('#anagram').val();
        splitted = inputTxt.split("");
        splitted.sort(); //first sort the array in order to generate permutations
        $('#AnagramTxtArea').append(splitted.join("") + " ");
        t = setInterval(GeneratePermutation,10);
    }
});
});

Respondido 27 ago 11, 23:08

@DanDinu: I updated my answer with a solution to your second problem. - Daniel Trebbien

works great but i can't really understand why. You're changing the button id to StopBtn and call $('#StopBtn').click() from GeneratePermtation(). Why does it still fire the SubmitBtn.click()? It's another id.. - Dan Dinu

@DanDinu: While it's a different ID, it's still the same element. The click handler is bound to the element. - Daniel Trebbien

I see, but then(by my logic) i should't change the id, just the text value from Submit to Send and viceversa. It doesn't work though... - Dan Dinu

@DanDinu: Just changing the text is fine. I am not sure why it isn't working for you. Perhaps double check that you replaced all occurrences of the original IDs with the new one. - Daniel Trebbien

Here you actually execute GeneratePermutation() at the time you call setInterval():

t = setInterval(GeneratePermutation(),10);

You have to pass a function to setInterval(). Do this instead:

t = setInterval(GeneratePermutation, 10);

Respondido 27 ago 11, 22:08

You must pass in the function name or an anonymous function as the first argument for setInterval. See MDN reference https://developer.mozilla.org/en/window.setInterval

t = setInterval(GeneratePermutation,10);

or

t = setInterval(function() { /* code */ }, 10);

proper syntax for setInterval:

var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
var intervalID = window.setInterval(code, delay);

dónde

  • intervalID es un ID de intervalo único que puede pasar a clearInterval ().
  • func is the function you want to be called repeatedly. code in the
  • alternate syntax, is a string of code you want to be executed repeatedly. (Using this syntax is not recommended for the same reasons as using eval()) delay is the number of milliseconds (thousandths of a second) that the setInterval() function should wait before each call to func. As with setTimeout, there is a minimum delay enforced.

Edit: This could be a problem, assuming you are trying to fire a click.

function GeneratePermutation() {
        splitted = AnagramObj.NextPermutation(splitted);
        if (splitted!=null)
            $('#AnagramTxtArea').append(splitted.join("") + " ");       
        else  
            //$('#StopBtn').click();
            // should be
            $('#StopBtn').trigger('click');

    }

Respondido 27 ago 11, 23:08

Estás seguro $('#StopBtn').click() is firing? Throw an alert() or console.log() in the function. See my edit as well - Trevor

yes, it's firing. i used breakpoints in chrome, but after it gets to the end of the click function code continues to execute - Dan Dinu

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.