JavaScript Timer Pause

2019-07-20 05:38发布

问题:

The code is below. How would you set a button to pause the timer and resume when pressing resume? The // marks below are where I'm placing my pause and resume tags. Thank you for all of your help!!

<head>
<script type="text/javascript">

var d1 = new Date();
d1.setHours(1,0,0);

function f(){
var h= d1.getHours();
var m= d1.getMinutes();
var s=d1.getSeconds();
m= (m<10)?"0"+m: m;
s= (s<10)? "0"+s : s;

var el= document.getElementById("inputid");
el.value= h+":"+m+":"+s;
d1.setSeconds(d1.getSeconds()-1);
if( h==0 && m==0 && s==0 ) clearTimeout(t)
var t= setTimeout("f()",1000);
}

</script>
</head>
<body>
<form><input type="text" id="inputid"></form>
<script type="text/javascript">f()</script>

//pause and resume buttons would go here.
</body>

回答1:

You can stop a timeout with clearTimeout() passing it the return from setTimeout or, in your case t.

Live example: http://jsfiddle.net/tJWmH/

Another pointer: dont pass a string to setTimeout, instead pass a function reference, so:

var t = setTimeout(f,1000)

in place of

var t = setTimeout("f()",1000);

if you're wondering why, search for "eval is evil".



回答2:

Another approach is: when the buttons is pressed, set a variable like paused. In your f function, if paused is true, simply return immediately.

setInterval(function(){
  if (paused) return;
  // update the dom
}, 1000);

input

<input type="button" value="Pause" onClick="window.paused=true" />

Here is a basic fiddle



回答3:

Try this:

var d1 = new Date();
d1.setHours(1,0,0);
var t;


function f() {
    var h= d1.getHours();
    var m= d1.getMinutes();
    var s=d1.getSeconds();
    m= (m < 10) ? ('0'+m) : m;
    s= (s < 10) ? ('0'+s) : s;

    var el= document.getElementById("inputid");
    el.value = h+":"+m+":"+s;

    if( h==0 && m==0 && s==0 ) {
        clearTimeout(t)
        return;   
    }
    d1.setSeconds(d1.getSeconds()-1);

    t= setTimeout(f,1000);

}

function pause() {
    clearTimeout(t);
}
function resume() {
    t= setTimeout(f,1000);
}
resume();

You just call pause() to pause it, and resume() to resume it. That's it! Notice that I am calling resume() once, just to start the counter.

EDIT: You must check if it reached zero before decrementing, and return so that pressing resume won't continue to work.



回答4:

This is not my code. I found it and use in my projects. Here's the original post: https://stackoverflow.com/a/3969760/1250044

Timer = function(callback, delay) {
  var timerId, start, remaining = delay;

  this.pause = function() {
    window.clearTimeout(timerId);
    remaining -= new Date() - start;
  };

  this.resume = function() {
    start = new Date();
    timerId = window.setTimeout(callback, remaining);
  };

  this.resume();
};

use:

var t = new Timer(function(){
 /* ... */
}, 500);

t.pause();
t.resume();