ディレクトリ 検索
AngularJS API Reference auto auto/service auto/service/$injector auto/service/$provide ng ng/directive ng/directive/a ng/directive/form ng/directive/input ng/directive/input[checkbox] ng/directive/input[date] ng/directive/input[dateTimeLocal] ng/directive/input[email] ng/directive/input[month] ng/directive/input[number] ng/directive/input[radio] ng/directive/input[text] ng/directive/input[time] ng/directive/input[url] ng/directive/input[week] ng/directive/ngApp ng/directive/ngBind ng/directive/ngBindHtml ng/directive/ngBindTemplate ng/directive/ngBlur ng/directive/ngChange ng/directive/ngChecked ng/directive/ngClass ng/directive/ngClassEven ng/directive/ngClassOdd ng/directive/ngClick ng/directive/ngCloak ng/directive/ngController ng/directive/ngCopy ng/directive/ngCsp ng/directive/ngCut ng/directive/ngDblclick ng/directive/ngDisabled ng/directive/ngFocus ng/directive/ngForm ng/directive/ngHide ng/directive/ngHref ng/directive/ngIf ng/directive/ngInclude ng/directive/ngInit ng/directive/ngKeydown ng/directive/ngKeypress ng/directive/ngKeyup ng/directive/ngList ng/directive/ngModel ng/directive/ngModelOptions ng/directive/ngMousedown ng/directive/ngMouseenter ng/directive/ngMouseleave ng/directive/ngMousemove ng/directive/ngMouseover ng/directive/ngMouseup ng/directive/ngNonBindable ng/directive/ngOpen ng/directive/ngPaste ng/directive/ngPluralize ng/directive/ngReadonly ng/directive/ngRepeat ng/directive/ngSelected ng/directive/ngShow ng/directive/ngSrc ng/directive/ngSrcset ng/directive/ngStyle ng/directive/ngSubmit ng/directive/ngSwitch ng/directive/ngTransclude ng/directive/ngValue ng/directive/script ng/directive/select ng/directive/textarea ng/filter ng/filter/currency ng/filter/date ng/filter/filter ng/filter/json ng/filter/limitTo ng/filter/lowercase ng/filter/number ng/filter/orderBy ng/filter/uppercase ng/function ng/function/angular.bind ng/function/angular.bootstrap ng/function/angular.copy ng/function/angular.element ng/function/angular.equals ng/function/angular.extend ng/function/angular.forEach ng/function/angular.fromJson ng/function/angular.identity ng/function/angular.injector ng/function/angular.isArray ng/function/angular.isDate ng/function/angular.isDefined ng/function/angular.isElement ng/function/angular.isFunction ng/function/angular.isNumber ng/function/angular.isObject ng/function/angular.isString ng/function/angular.isUndefined ng/function/angular.lowercase ng/function/angular.module ng/function/angular.noop ng/function/angular.toJson ng/function/angular.uppercase ng/object ng/object/angular.version ng/provider ng/provider/$animateProvider ng/provider/$compileProvider ng/provider/$controllerProvider ng/provider/$filterProvider ng/provider/$httpProvider ng/provider/$interpolateProvider ng/provider/$locationProvider ng/provider/$logProvider ng/provider/$parseProvider ng/provider/$rootScopeProvider ng/provider/$sceDelegateProvider ng/provider/$sceProvider ng/service ng/service/$anchorScroll ng/service/$animate ng/service/$cacheFactory ng/service/$compile ng/service/$controller ng/service/$document ng/service/$exceptionHandler ng/service/$filter ng/service/$http ng/service/$httpBackend ng/service/$interpolate ng/service/$interval ng/service/$locale ng/service/$location ng/service/$log ng/service/$parse ng/service/$q ng/service/$rootElement ng/service/$rootScope ng/service/$sce ng/service/$sceDelegate ng/service/$templateCache ng/service/$timeout ng/service/$window ng/type ng/type/$cacheFactory.Cache ng/type/$compile.directive.Attributes ng/type/$rootScope.Scope ng/type/angular.Module ng/type/form.FormController ng/type/ngModel.NgModelController ngAnimate ngAnimate/provider ngAnimate/provider/$animateProvider ngAnimate/service ngAnimate/service/$animate ngCookies ngCookies/service ngCookies/service/$cookies ngCookies/service/$cookieStore ngMessages ngMessages/directive ngMessages/directive/ngMessage ngMessages/directive/ngMessages ngMock ngMock/function ngMock/function/angular.mock.dump ngMock/function/angular.mock.inject ngMock/function/angular.mock.module ngMock/object ngMock/object/angular.mock ngMock/provider ngMock/provider/$exceptionHandlerProvider ngMock/service ngMock/service/$exceptionHandler ngMock/service/$httpBackend ngMock/service/$interval ngMock/service/$log ngMock/service/$timeout ngMock/type ngMock/type/angular.mock.TzDate ngMockE2E ngMockE2E/service ngMockE2E/service/$httpBackend ngResource ngResource/service ngResource/service/$resource ngRoute ngRoute/directive ngRoute/directive/ngView ngRoute/provider ngRoute/provider/$routeProvider ngRoute/service ngRoute/service/$route ngRoute/service/$routeParams ngSanitize ngSanitize/filter ngSanitize/filter/linky ngSanitize/service ngSanitize/service/$sanitize ngTouch ngTouch/directive ngTouch/directive/ngClick ngTouch/directive/ngSwipeLeft ngTouch/directive/ngSwipeRight ngTouch/service ngTouch/service/$swipe
テキスト

AngularJS: API: ng/service/$interval


$interval

  1. - service in module ng

Angular's wrapper for window.setInterval. The fn function is executed every delay milliseconds.

The return value of registering an interval function is a promise. This promise will be notified upon each tick of the interval, and will be resolved after count iterations, or run indefinitely if count is not defined. The value of the notification will be the number of iterations that have run. To cancel an interval, call $interval.cancel(promise).

In tests you can use $interval.flush(millis) to move forward by millis milliseconds and trigger any functions scheduled to run in that time.

注意: Intervals created by this service must be explicitly destroyed when you are finished with them. In particular they are not automatically destroyed when a controller's scope or a directive's element are destroyed. You should take this into consideration and make sure to always cancel the interval at the appropriate moment. See the example below for more details on how and when to do this.

用法

$interval(fn, delay, [count], [invokeApply]);

参数

参数 类型 详述
fn function()

A function that should be called repeatedly.

delay number

Number of milliseconds between each function call.

count
(可选)
number

Number of times to repeat. If not set, or 0, will repeat indefinitely.

invokeApply
(可选)
boolean

If set to false skips model dirty checking, otherwise will invoke fn within the $apply block.

返回值

promise

A promise which will be notified on each iteration.

方法

  • cancel(promise);

    Cancels a task associated with the promise.

    参数

    参数 类型 详述
    promise promise

    returned by the $interval function.

    返回值

    boolean

    返回值true if the task was successfully canceled.

示例

index.html
<script>
angular.module('intervalExample', [])
  .controller('ExampleController', ['$scope', '$interval',
    Function($scope, $interval) {
      $scope.format = 'M/d/yy h:mm:ss a';
      $scope.blood_1 = 100;
      $scope.blood_2 = 120;

      var stop;
      $scope.fight = Function() {
        // Don't start a new fight if we are already fighting
        if ( angular.isDefined(stop) ) return;

      stop = $interval(Function() {
        if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
          $scope.blood_1 = $scope.blood_1 - 3;
          $scope.blood_2 = $scope.blood_2 - 4;
        } else {
          $scope.stopFight();
        }
      }, 100);
    };

    $scope.stopFight = Function() {
      if (angular.isDefined(stop)) {
        $interval.cancel(stop);
        stop = undefined;
      }
    };

    $scope.resetFight = Function() {
      $scope.blood_1 = 100;
      $scope.blood_2 = 120;
    };

    $scope.$on('$destroy', Function() {
      // Make sure that the interval nis destroyed too
      $scope.stopFight();
    });
  })
  // Register the 'myCurrentTime' directive factory method.
  // We inject $interval and dateFilter service since the factory method is DI.
  .Directive('myCurrentTime', ['$interval', 'dateFilter',
    Function($interval, dateFilter) {
      // return the directive link function. (compile function not needed)
      return Function(scope, element, attrs) {
        var format,  // date format
            stopTime; // so that we can cancel the time updates

        // used to update the UI
        Function updateTime() {
          element.text(dateFilter(new Date(), format));
        }

        // watch the expression, and update the UI on change.
        scope.$watch(attrs.myCurrentTime, Function(value) {
          format = value;
          updateTime();
        });

        stopTime = $interval(updateTime, 1000);

        // listen on DOM destroy (removal) event, and cancel the next UI update
        // to prevent updating time after the DOM element was removed.
        element.on('$destroy', Function() {
          $interval.cancel(stopTime);
        });
      }
    });</script>

<div><div ng-controller="ExampleController">
  Date format: <input ng-model="format"> <hr/>
  Current time is: <span my-current-time="format"></span>
  <hr/>
  Blood 1 : <font color='red'>{{blood_1}}</font>
  Blood 2 : <font color='red'>{{blood_2}}</font>
  <button Type="button" data-ng-click="fight()">Fight</button>
  <button Type="button" data-ng-click="stopFight()">StopFight</button>
  <button Type="button" data-ng-click="resetFight()">resetFight</button></div></div>
前の記事: 次の記事: