Search code examples
javascripthttp-redirectdelay

Interupt a javascript redirect with a delay


Im currently using a simple javascript redirect (called on load) with a delay to automatically redirect users from older articles to newer ones in a corporate wiki. However, Id like users to be able to stop the autoredirect so they can access the older data if needed.

How could I modify this code to achieve that?

<script type="text/javascript">
var h = setTimeout("iiredirect()", 2000);
function iiredirect() { window.location = "that new location"; }
</script>

Solution

  • Assuming button is a reference to your cancel redirection button.

    var timeout = setTimeout(function() {
        window.location = "that new location";
    }, 2000);
    
    button.addEventListener('click', function() {
        clearTimeout(timeout);
    }, false);