Javascript countdown timer that stops when window is not in focus

前端 未结 2 1827
一向
一向 2020-12-07 00:01

Ok , I\'m having trouble to solve this , I\'m a php / C# web developer , and have no experience or knowledge in Javascript, I have to do just this one thing that needs Javas

2条回答
  •  余生分开走
    2020-12-07 00:41

    You could do this using jQuery.
    Recycling an old Stackoverflow post, try this:

    var window_focus;
    var counter = 1000;
    
    // on focus, set window_focus = true.
    $(window).focus(function() {
        window_focus = true;
    });
    
    // when the window loses focus, set window_focus to false
    $(window).focusout(function() {
        window_focus = false;
    });
    
    // this is set to the ('click' function, but you could start the interval/timer in a jQuery.ready function: http://api.jquery.com/ready/
    $(document).one('click',function() {
        // Run this function every second. Decrement counter if window_focus is true.
        setInterval(function() {
            $('body').append('Count: ' + counter + '
    '); if(window_focus) { counter = counter-1; } }, 1000); });

    Demo and old post
    DEMO | Old So post

    Update
    Probably because the demo runs in 4 iframes, the $(window).focus bit only works on the iframe actually running the code (the bottom-right window).

    jQuery
    jQuery.com (How jQuery works) | Example (back to basics halfway down the page) | If you use the 2nd link, also read this

提交回复
热议问题