Simple module which detecting when user gone away by listening useractions (mouse moves, key presses and scrolls).
At first, to decrease components concurency, we need module which can incapsulate simple state.
var awayModule = {
box: $('.box .overlay'),
show: function(){
awayModule.box.fadeIn();
},
hide: function(){
awayModule.box.fadeOut();
}
};
var userActions = $(document).stream('mousemove, mousedown, keydown, scroll');
// Here we hiding state of timeout into awayModule
// Here we can use not pure functions
awayModule.aways = Warden.Stream(function(trigger) {
var timeout;
function start(){
timeout = setTimeout(trigger, 5000);
}
this.restart = function(){
clearTimeout(timeout);
start();
}
start(5000);
}, awayModule);
awayModule.aways
.listen(awayModule.show);
// Naive implementation
userActions
.listen(awayModule.restart)
.listen(awayModule.hide);
// You can see that awayModule.hide will invoke every time when we will make user action
// Optimal way to prevent unneccesary invokations is use .after method
userActions.after(awayModule.aways)
.listen(awayModule.hide);
//this stream will invoke awayModule.hide only when it neccessary