How to create a circular countdown timer using HTML, CSS or JavaScript?

后端 未结 2 1680
庸人自扰
庸人自扰 2021-01-30 09:35

Currently, I am working on a quiz game and in that, for each question, I wish to place a countdown timer. I got some plugins, but I wish if I could create it myself. What I am

2条回答
  •  清酒与你
    2021-01-30 10:21

    Here is something i was playing around with a while ago. It uses a combination of SVG, css transitions and javascript. You should be able to rip it apart and use as a starting point...

    /**
    * The setTimeout({},0) is a workaround for what appears to be a bug in StackSnippets.
    * It should not be required. See JSFiddle version.
    */
    
    setTimeout(function() { 
    
      var time = 10; /* how long the timer will run (seconds) */
      var initialOffset = '440';
      var i = 1
    
      /* Need initial run as interval hasn't yet occured... */
      $('.circle_animation').css('stroke-dashoffset', initialOffset-(1*(initialOffset/time)));
    
      var interval = setInterval(function() {
          $('h2').text(i);
          if (i == time) {  	
            clearInterval(interval);
            return;
          }
          $('.circle_animation').css('stroke-dashoffset', initialOffset-((i+1)*(initialOffset/time)));
          i++;  
      }, 1000);
    
    }, 0)
    .item {
        position: relative;
        float: left;
    }
    
    .item h2 {
        text-align:center;
        position: absolute;
        line-height: 125px;
        width: 100%;
    }
    
    svg {
       -webkit-transform: rotate(-90deg);
        transform: rotate(-90deg);
    }
    
    .circle_animation {
      stroke-dasharray: 440; /* this value is the pixel circumference of the circle */
      stroke-dashoffset: 440;
      transition: all 1s linear;
    }
    
    

    0

    Layer 1

    JSFiddle version

提交回复
热议问题