Trying to implement clearInterval to stop the continuous display of user-inputted strings.
This isn't an interval ID issue, as I have defined the setInterval function as a variable already (and still not working):
oldHandle = setInterval(function () {
But I'm trying to link the clearInterval function to a button, so that when it's pressed, the display will stop looping thru the user inputted strings.
Fiddle
HTML:
<h1 id='output'></h1>
<title>FORM</title>
<form id="frm">
<input id="txt" type="text" placeholder="Type something tasty..." name="text">
<label>1 at a time:
<input id='autoListen' type="checkbox" name="autoListen">
</label>
<input id='submitBtn' type="submit" value="OK">
<input type="button" value="Stop" onclick="stopDisplay()">
<div class="controlbox">
<div class="controlpanel"></div>
</div>
</form>
JS:
$(document).ready(function () {
var txtBox = $('#txt');
var frm = $('#frm');
var output = $('#output');
var subBtn = $('#submitBtn');
var container = [];
var oldHandle;
frm.submit(function (event) {
event.preventDefault();
var result = txtBox.val();
var $entry = $("<p>" + result + "</p>");
container.push(result);
$(".controlpanel").append($entry);
var i = 0;
clearInterval(oldHandle);
oldHandle = setInterval(function () {
if (i >= container.length) {
i = 0;
}
if (container.length > 0) {
output.text(container[i]);
console.log(container[i]);
++i;
} else {
output.empty();
clearInterval(oldHandle);
}
}, 2500)
txtBox.val('');
});
$('#autoListen').click(function () {
if ($('#autoListen').is(':checked')) {
subBtn.hide();
output.text(txtBox.val());
txtBox.keyup(function () {
output.text(txtBox.val());
})
} else {
subBtn.show();
txtBox.unbind('keyup');
}
});
$(".controlbox").on('dblclick', 'p', function() {
var $entry = $(this);
container.splice($entry.index(), 1);
$entry.remove();
});
function stopDisplay(){
clearInterval(oldHandle);
};
});
Any ideas as to where I'm going wrong??? Is this a scope issue? Am I defining the clearInterval function in an improper place? Or maybe my button isn't set up properly? I tried following clearInterval examples I found, to no avail...
Note: The Stop button can be found on Line 10 of HTML, the setInterval function on Line 20 of JS, and the stopDisplay/clearInterval function on line 60 of JS
Also: feel free to try out the interface - type in multiple strings, they'll display and re-display on constant loop. I'm trying to get them to stop looping thru the display upon the click of the stop button...