0

我的最终目标是创建一个计时器,以用户提供的间隔产生声音。例如,他们在一个字段中输入 10,然后每 10 秒发出一次哔声。现在,我只是无法让 setInterval 在范围内显示效果。非常感谢任何让我重回正轨的帮助。谢谢!

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

});
4

3 回答 3

1

您的代码按原样工作,但如果您进行了一些更改,它会更明显:

http://jsfiddle.net/PxENF/3/

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

});
于 2013-01-07T21:53:45.553 回答
0
$('#go').click(function() {
    interval = $('#ping_val').val();
    $('#ping_alert').text('The ping will sound every ' + interval + ' milliseconds.');
    setInterval(timer, interval); 
  });
于 2013-01-07T21:51:40.627 回答
0

您可以使间隔自支持,而无需声明全局变量:

$("#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); 
  });

请记住,每次单击“开始”时都会开始一个新的间隔。这些会互相干扰。这会更好:

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); 
  });
于 2013-01-07T22:14:58.273 回答