javascript countdown timer pause resume

前端 未结 1 776
抹茶落季
抹茶落季 2021-01-06 23:51

At first my countdown timer has no pause and resume function and the timer runs just fine. Now I just added the feature, have no problem pausing but having problem resuming

相关标签:
1条回答
  • 2021-01-07 00:19

    I wrote a little timer for you to get into it ;-)

    and a working example here: http://jsfiddle.net/rnQ2W/2/

    var CountDown = (function ($) {
        // Length ms 
        var TimeOut = 10000;
        // Interval ms
        var TimeGap = 1000;
    
        var CurrentTime = ( new Date() ).getTime();
        var EndTime = ( new Date() ).getTime() + TimeOut;
    
        var GuiTimer = $('#countdown');
        var GuiPause = $('#pause');
        var GuiResume = $('#resume').hide();
    
        var Running = true;
    
        var UpdateTimer = function() {
            // Run till timeout
            if( CurrentTime + TimeGap < EndTime ) {
                setTimeout( UpdateTimer, TimeGap );
            }
            // Countdown if running
            if( Running ) {
                CurrentTime += TimeGap;
                if( CurrentTime >= EndTime ) {
                    GuiTimer.css('color','red');
                }
            }
            // Update Gui
            var Time = new Date();
            Time.setTime( EndTime - CurrentTime );
            var Minutes = Time.getMinutes();
            var Seconds = Time.getSeconds();
    
            GuiTimer.html( 
                (Minutes < 10 ? '0' : '') + Minutes 
                + ':' 
                + (Seconds < 10 ? '0' : '') + Seconds );
        };
    
        var Pause = function() {
            Running = false;
            GuiPause.hide();
            GuiResume.show();
        };
    
        var Resume = function() {
            Running = true;
            GuiPause.show();
            GuiResume.hide();
        };
    
        var Start = function( Timeout ) {
            TimeOut = Timeout;
            CurrentTime = ( new Date() ).getTime();
            EndTime = ( new Date() ).getTime() + TimeOut;
            UpdateTimer();
        };
    
        return {
            Pause: Pause,
            Resume: Resume,
            Start: Start
        };
    })(jQuery);
    
    jQuery('#pause').on('click',CountDown.Pause);
    jQuery('#resume').on('click',CountDown.Resume);
    
    // ms
    CountDown.Start(120000);
    
    0 讨论(0)
提交回复
热议问题