1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

java to refresh a url with timer

Discussion in 'JavaScript' started by irdogg, Apr 17, 2013.

  1. #1
    what is the best way? thank you for your help :)

    <script>
        var time = new Date().getTime();
        $(document.body).bind("mousemove keypress", function(e) {
            time = new Date().getTime();
        });
     
        function refresh() {
            if(new Date().getTime() - time >= 60000)
                window.location.reload(true);
            else
                setTimeout(refresh, 10000);
        }
     
        setTimeout(refresh, 10000);
    </script>
    Code (markup):
    or

    var refresh_rate = 200; //<-- In seconds, change to your needs
    var last_user_action = 0;
    var has_focus = false;
    var lost_focus_count = 0;
    var focus_margin = 10; // If we lose focus more then the margin we want to refresh
     
     
    function reset() {
        last_user_action = 0;
        console.log("Reset");
    }
     
    function windowHasFocus() {
        has_focus = true;
    }
     
    function windowLostFocus() {
        has_focus = false;
        lost_focus_count++;
        console.log(lost_focus_count + " <~ Lost Focus");
    }
     
    setInterval(function () {
        last_user_action++;
        refreshCheck();
    }, 1000);
     
    function refreshCheck() {
        var focus = window.onfocus;
        if ((last_user_action >= refresh_rate && !has_focus && document.readyState == "complete") || lost_focus_count > focus_margin) {
            window.location.reload(); // If this is called no reset is needed
            reset(); // We want to reset just to make sure the location reload is not called.
        }
     
    }
    window.addEventListener("focus", windowHasFocus, false);
    window.addEventListener("blur", windowLostFocus, false);
    window.addEventListener("click", reset, false);
    window.addEventListener("mousemove", reset, false);
    window.addEventListener("keypress", reset, false);
    Code (markup):
     
    irdogg, Apr 17, 2013 IP
  2. diplox

    diplox Peon

    Messages:
    8
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    1
    #2
    Personally I'd say the first, not only is it considerably simpler, but in the latter you're refreshing the page using setInterval, and the timer will be destroyed every time the page is reloaded anyway so honestly setTimeout makes more sense in this case. Also using setInterval in this way could potentially create memory leaks on older browsers if the handle isn't freed on reload.
     
    diplox, Apr 19, 2013 IP