Can someone help me decipher the following code snippet?
function setIdle(cb, seconds) {
var timer;
var interval = seconds * 1000;
function refresh() {
clearInterval(timer);
timer = setTimeout(cb, interval);
};
$(document).on('keypress, click', refresh);
refresh();
}
setIdle(function() {
location.href = location.href;
}, 5);
The setIdle
function takes two arguments. It contains a nested function called refresh
which resets a timer on a scheduled event. Each time an event like click
or keypress
occurs, the refresh()
function is triggered.
At the end of the code block, another call to setIdle
is made with a different function and a value of 5
, specifying the duration of the timer in seconds. This new function sets the page to automatically refresh (location.href = location.href;
) every 5 seconds.
In case I add an additional function:
setIdle(function() {
console.log('hi');
}, 1);
Why does this second function execute only once instead of every second as the previous one?