user3223205
user3223205

Reputation:

reset timer on click using javascript

i have this JS Code:

<script>
$(document).ready(function () {
    window.setTimeout(function () {
        $('#logout_warning').reveal();
    }, 6000)
});
$(document).ready(function () {
    window.setTimeout(function () {
        location.href = "/login/logout.php?url=/index.php?r=inactivity";
    }, 12000)
});
</script>

it displays a DIV after X Seconds then redirects the page after Y Seconds

is there a way to create a link that will reset the timer back to X seconds and without having to refresh the page?

Upvotes: 1

Views: 344

Answers (1)

Paul S.
Paul S.

Reputation: 66304

You could write a wrapper for setTimeout like this

function myTimeout(fn, delay) {
    var o = {i: null};
    o.cancel = function () {
        if (o.i) window.clearTimeout(o.i);
    };
    o.reset = function () {
        if (o.i) window.clearTimeout(o.i);
        o.i = window.setTimeout(fn, delay);
    };
    o.reset();
    return o;
}

Then

// common (ancestor?) scope
var t;

// descendant scope, set
t = myTimeout(function () {
    $('#logout_warning').reveal();
}, 6000);

// descendant scope where you attach listener to your link
$('#my_link').on('click', function () {
    t.reset(); // re-start the timeout
    return false;
});

Upvotes: 1

Related Questions