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();
}
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.
Here you actually execute
GeneratePermutation()
at the time you call setInterval():You have to pass a function to setInterval(). Do this instead:
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
or
proper syntax for setInterval:
where
Edit: This could be a problem, assuming you are trying to fire a click.
You need to pass the function object itself to
setInterval()
, not the result of a call to the function:EDIT: On your second question, what you can do is check whether the interval is running. If it is, then cancel it: