user4708518
user4708518

Reputation:

Jquery settimeout not waiting to redirect

Well, I am currently trying to set a timer on a redirect to another webpage, however when I use settimeout it does not work.

    setTimeout(function() {
        window.location.replace("https://github.com/Riggster"");
    }, 2000);

It redirects me, however it does not wait two seconds. And I am not sure why.

$(document).ready(function () {
    var gsb = $('.github-side-bar');
    var rd = $('.redirectnotice');
    gsb.on('click' , function() {
        $('html, body').animate({
            scrollTop: 0
        }, 500);
        rd.show('slow');
        setTimeout(function() {
            window.location.replace("https://github.com/Riggster"");
        }, 2000);
    });

Associated HTML:

<a href="#top" class="back-to-top"><img src="./asset/img/btt.ico" width="32" height="32" /></a>
<a href="https://twitter.com/euanriggans" class="twitter-side-bar"><img src="./asset/img/twitter.ico" width="32" height="32" /></a>
<a href="https://github.com/Riggster" class="github-side-bar"><img src="./asset/img/github.ico" width="32" height="32" /></a>
<div class="redirectnotice"><img src="./asset/img/loading.svg" width="200" height="200" /><H1>Redirecting you</H1></div>

Upvotes: 0

Views: 55

Answers (2)

adeneo
adeneo

Reputation: 318202

You need to prevent the default action of the anchor

gsb.on('click' , function(e) {

    e.preventDefault();

    $('html, body').animate({
        scrollTop: 0
    }, 500);
    rd.show('slow');
    setTimeout(function() {
        window.location.replace("https://www.google.com");
    }, 2000);
});

Upvotes: 2

Justin
Justin

Reputation: 299

You may need to show us more of your code to track down the issue. What you have there looks fine. I tested it here and it works perfectly in Chrome, FF, and IE.

<!DOCTYPE html>
<html>  
    <head>      
        <meta charset="UTF-8">  
        <title>Test</title>     
    </head>
    <body>  
        <div><h1>wait, then redirect...</h1></div>  
        <script>
            setTimeout(function() {
                window.location.replace("https://www.google.com");
            }, 2000);
        </script>
    </body>
</html>

Upvotes: 0

Related Questions