views:

87

answers:

2

Hello !

I have some function taht is caller periodically:

var func = function() {
    alert('Hello world!');
};
func.periodical(5000);

This function is also called with click event:

$('element').addEvent('click', function(){
    func();
});

The timer starts and counts 2500msec, then I click $('element'), func() is executed and I want right now to reset the timer that func() will not be called in next 2500msec but in following 5000msec.

How to do that ?

A: 

I think the simplest thing to do would be to have the function return if it detects that it has been less than 5000 milliseconds since the last time it ran.

var func = (function() {
  var ts = new Date();
  return function(force) {
    var now = new Date();
    if (!force && now - ts < 5000)
      return;
    alert("Hi!");
    ts = now;
  };
})();
func.periodical(5000);

$('element').addEvent('click', function() {
  func(true);
});

In the event handler, the function is called with a parameter that forces it to ignore the timer. This mechanism is a little fragile of course.

Pointy
This is not the MooTools-way of doing things like that.
Oskar Krawczyk
Well this has the advantage that it keeps the timer "on time" more than the other answer given. Starting over with a new 5 second timeout seems much worse to me.
Pointy
+1  A: 

You could delete the periodical interval, and set it again when the element is clicked. To avoid carrying an extra variable around, you could store the timer reference in the function object itself.

func.timer = func.periodical(5000);

$('element').addEvent('click', function() {
    func();
    $clear(func.timer);
    func.timer = func.periodical(5000);
});
Anurag