How to make timer in JavaScript

7

I need help to make a timer for a page, and it must be different for each difficulty of a game, for example, for easy mode has 1 min, for intermediate has 4 min, and for difficult 8 minutes .

    
asked by anonymous 15.05.2016 / 13:16

3 answers

11

You can make an object Timer and then create new instances each time you need them. For example:

var button = document.querySelector('button');
var mostrador = document.querySelector('#mostrador');

button.addEventListener('click', function() {
    new Timer(1, mostrador, function() {
        alert('O tempo acabou!');
    }).start();
});

function Timer(mins, target, cb) {
    this.counter = mins * 60;
    this.target = target;
    this.callback = cb;
}
Timer.prototype.pad = function(s) {
    return (s < 10) ? '0' + s : s;
}
Timer.prototype.start = function(s) {
    this.count();
}
Timer.prototype.stop = function(s) {
    this.count();
}
Timer.prototype.done = function(s) {
    if (this.callback) this.callback();
}
Timer.prototype.display = function(s) {
    this.target.innerHTML = this.pad(s);
}
Timer.prototype.count = function(s) {
    var self = this;
    self.display.call(self, self.counter);
    self.counter--;
    var clock = setInterval(function() {
        self.display(self.counter);
        self.counter--;
        if (self.counter < 0) {
            clearInterval(clock);
            self.done.call(self);
        }
    }, 1000);
}
<div id="mostrador"></div>
<button>1 minuto</button>

jsFiddle: link

    
15.05.2016 / 14:07
2

You can use the setInterval

  setInterval(function(){
    alert("Olá"); 
  }, 2000);

Enter the action you want to perform between the keys (an alert in the example). and after the closing key specify the time in milliseconds and each time that count is complete (2 seconds in the example) it calls the desired action.

FiddleJS with example.

    
15.05.2016 / 13:31
1

Two simple options (2000 ms):

requestAnimationFrame

  

[ requestAnimationFrame ] tells the browser that you want to perform an animation and requests that the browser call a specified function to update an animation before the next repaint.

window.requestAnimationFrame(loop);
var timer_RAF = performance.now();
function loop (){
  passed = performance.now() - timer_RAF;
  if(passed >= 2000){
    console.log('requestAnimationFrame', passed);
    timer_RAF= performance.now();
    // seu codigo a ser executado a cada 2000ms
  }
  window.requestAnimationFrame(loop);
}

setInterval

var timer_interval = performance.now();
setInterval(function(){
    console.log('setInterval', performance.now() - timer_interval);
    timer_interval = performance.now();
    // seu codigo a ser executado a cada 2000ms
 }, 2000);
    
27.05.2016 / 22:49