首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >角度倒计时计时器

角度倒计时计时器
EN

Stack Overflow用户
提问于 2018-06-20 08:16:45
回答 2查看 1.4K关注 0票数 0

我偶然发现了这个角度计时器,它对我来说工作得很好。然而,当它到达倒计时日期时,我似乎无法成功地让它停止。我基本上想让它在00:00:00停止。有帮助吗?Angular Countdown Timer

代码语言:javascript
复制
Check Codepen for code
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-06-20 08:37:57

如果我正确理解问题,这里的解决方案,它不是用CoffeScript编写的(然而,它很容易适应),它是用普通的旧javascript编写的。我对编辑进行了注释

代码语言:javascript
复制
(function() {
  angular.module('app', []).directive('countdown', [
    'Util',
    '$interval',
    function(Util,
    $interval) {
      return {
        restrict: 'A',
        scope: {
          date: '@'
        },
        link: function(scope,
    element) {
          var future;
          future = new Date(scope.date);
          //----you need to keep a reference to $interval----
          var int = $interval(function() {
            var diff;
            diff = Math.floor((future.getTime() - new Date().getTime()) / 1000);
            //----just check for the value of 'diff' when it becomes 0 you have to clear $interval
            if(diff===0) {
              $interval.cancel(int);
              return element.text("BOOM!")
            }
            return element.text(Util.dhms(diff));
          },
    1000);
        }
      };
    }
  ]).factory('Util', [
    function() {
      return {
        dhms: function(t) {
          var days,
    hours,
    minutes,
    seconds;
          days = Math.floor(t / 86400);
          t -= days * 86400;
          hours = Math.floor(t / 3600) % 24;
          t -= hours * 3600;
          minutes = Math.floor(t / 60) % 60;
          t -= minutes * 60;
          seconds = t % 60;
          return [days + 'd',
    hours + 'h',
    minutes + 'm',
    seconds + 's'].join(' ');
        }
      };
    }
  ]);

}).call(this);
票数 0
EN

Stack Overflow用户

发布于 2018-06-20 09:01:15

我相信这将为您工作,在Coffee脚本中,您应该能够将其复制到您的示例中。关键是当diff达到零时打印输出,然后取消计时器。

代码语言:javascript
复制
angular.module 'app', []

.directive 'countdown', ['Util', '$interval', (Util, $interval) ->
  restrict: 'A'
  scope:
    date: '@'
  link: (scope, element) ->    
    future = new Date scope.date
    int = $interval ->
      diff = Math.floor (future.getTime() - new Date().getTime()) / 1000
      if (diff >= 0)
        element.text  Util.dhms diff
      else
        element.text  Util.dhms 0
        $interval.cancel int
    , 1000
    return
]

.factory 'Util', [ ->
  {
    dhms: (t) ->
      days = Math.floor t / 86400
      t -= days * 86400
      hours = Math.floor(t / 3600) % 24
      t -= hours * 3600
      minutes = Math.floor(t / 60) % 60
      t -= minutes * 60
      seconds = t % 60
      [ days + 'd', hours + 'h', minutes + 'm', seconds + 's' ].join ' '
  }
]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50938533

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档