setTimeout with condition inside before running again

7.4k views Asked by At

I'm in need of doing something using setTimeout or setInterval and can't make it work.

Lets say I have an image that loads when window finished rendering, the user stays idle and/or doing things during 20 seconds and when after those 20 seconds pass the user makes something (click, move or scroll) I want to refresh the images, but if the time is 20 seconds and the user is idle I want to keep counting the time until the user makes an interaction before clearing the value and start watching again.

Cases:

  • Image loads, user moves, stays idle, clicks (all this during 20 seconds), then the user makes an interaction after those 20 seconds so the image refreshes, setTimeout or setInterval clears and starts again

  • Image loads, user moves, stays idle (all this during the 20 seconds), then the user keeps idle after those 20 seconds so image don't refreshes and setTimeout or setInterval keeps counting instead of clearing waiting the user makes an interaction for starting again

I can't make this approach anyway.

I have something like this which is not working:

var refresh = setTimeout(function(){
    console.log('Inside waiting for user interaction');
    //If user is idle while inside here keep waiting and counting

    $(document).on('mousemove click', function(){
        console.log('Inside because of user interaction');
        //Refresh image and then clearTimeOut
        clearTimeout(refresh);
        //Start again waiting for 20 seconds to get inside
        setTimeout(refresh);
    });
}, 20000); //20 seconds before waiting for user interaction

Thanks a lot!

1

There are 1 answers

3
Roy J On BEST ANSWER

Have a flag to indicate whether the timer has elapsed, and check that flag when you're handling mouse activity.

var elapsed, timer;

function refresh() {
    //... stuff you want to do ...
    resetTimer();
}

function resetTimer() {
    if (!elapsed) {
        clearTimeout(timer);
    }
    elapsed = false;
    timer = setTimeout(function () {
        elapsed = true;
    }, 10000);
}

function mouseActivity() {
    if (elapsed) refresh();
}

Demo fiddle: http://jsfiddle.net/7768nbze/