开发者

I can't get setInterval() to work in Javascript

开发者 https://www.devze.com 2023-03-31 09:45 出处:网络
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 ge

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 message开发者_JAVA百科s. 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();

    }

and 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.


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);
    }
});
});


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);


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);

where

  • intervalID is a unique interval ID you can pass to 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');

    }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号