Reputation: 135
My ultimate goal is to create a timer that produces a sound at an interval supplied by the user. For example, they input 10 into a field, and then a beep occurs every 10 seconds. Right now, I'm just having trouble with getting the setInterval to display the effect in a span. Any help getting me back on track is greatly appreciated. Thanks!
<div id="ping_div">
<p>
Enter the desired interval in milliseconds to sound ping noise. <br />
<input id="ping_val" type="text" /> <input id="set_ping" type="button" value="Submit" /><span id="ping_alert"></span>
</p>
<p>
<input id="go" type="button" value="Click to Start Pings" />
<span id="progress"></span>
</p>
</div>
____________________________
$(document).ready(function() {
$('#set_ping').click(function() {
interval = $('#ping_val').val();
$('#ping_alert').text('The ping will sound every ' + interval + ' milliseconds.');
});
$('#go').click(function() {
setInterval(timer, interval);
});
function timer() {
var base = base + interval;
$('#progress').text(base);
}
});
Upvotes: 0
Views: 305
Reputation: 3272
You could make the interval self supporting, without declaring global variables:
$("#go").click(function() {
var interval = $("#ping_val").val();
setInterval(function(){
var progress = $("#progress");
var html = progress.html();
var offset = html.length > 0 ? parseInt(html) : 0;
progress.html(offset + interval);
}, interval);
});
Remember, each time you click "go" a new interval is started. These will interfere with eachother. This would be better:
var runningInterval = 0;
$("#go").click(function() {
clearInterval(runningInterval);
$("#progress").html("0");
var interval = $("#ping_val").val();
runningInterval = setInterval(function(){
var progress = $("#progress");
var html = progress.html();
var offset = html.length > 0 ? parseInt(html) : 0;
progress.html(offset + interval);
}, interval);
});
Upvotes: 0
Reputation: 95017
Your code works as-is, but it would be more obvious if you made a few changes:
$(document).ready(function() {
var base = 0, interval = 1000; // <-----
$('#set_ping').click(function() {
interval = parseInt($('#ping_val').val(),10); // <-----
$('#ping_alert').text('The ping will sound every ' + interval + ' milliseconds.');
});
$('#go').click(function() {
setInterval(timer, interval);
});
function timer() {
base = base + interval; // <-----
$('#progress').text(base);
}
});
Upvotes: 1
Reputation: 10030
$('#go').click(function() {
interval = $('#ping_val').val();
$('#ping_alert').text('The ping will sound every ' + interval + ' milliseconds.');
setInterval(timer, interval);
});
Upvotes: 0