0

I am trying to understand this code:

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);

setIdle takes two arguments. Inside its function it has a function refresh that clears a timer on a Timeout function. Now every time when an event happens (click, keypress) refresh() gets called.

and then finally this function gets called passing in another function and and int value (5) which later will be the amount of seconds for the timer. In that other function which later is represented through cb the page will be refreshed (location.href = location.href;).

This causes an automaticpage refresh every 5 seconds.

So now I don't understand if I put an additional function:

setIdle(function() {
        console.log('hi');
    }, 1);

Why is the second function only called once and not every second like the other one?

Tom
  • 2,545
  • 5
  • 31
  • 71
  • 1
    You might find a similar question interesting: [Detecting idle time in JavaScript elegantly](http://stackoverflow.com/questions/667555/detecting-idle-time-in-javascript-elegantly). – Yogi Apr 14 '16 at 16:25

1 Answers1

1

setIdle doesn't run the callback function every 5 seconds. It runs it once, 5 seconds after you call setIdle, and if you type or click something the timeout gets pushed back again. So it runs it once, when you've been idle for 5 seconds.

The reason the page refreshes every 5 seconds is because the callback function reloads the page, and reloading the page runs all the Javascript in the page again, so that calls setIdle() again.

But your second use of setIdle doesn't reload the page, so it just logs hi once.

If you want to do something repeatedly every N seconds, use setInterval rather than setTimeout.

BTW, clearInterval should be clearTimeout. In most browser they're currently interchangeable, but there's no guarantee. See Are clearTimeout and clearInterval the same?

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612