1. 程式人生 > 實用技巧 >定時執行函式並最終關閉定時器

定時執行函式並最終關閉定時器

<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="../lib/bootstrap-3.3.7/css/bootstrap.min.css">
    <script src="../lib/jquery/jquery.min.js"></script>
    <script src="../lib/bootstrap-3.3.7/js/bootstrap.min.js"></script>
    <script src="../lib/angular/angular.js"></script>
    <script>
        var app = angular.module('app', []);
        app.controller('myCtrl', function ($scope) {
            var arr=[1,4,3,2,4,6];
            var i = 0;       //在外面定義一個變數作為判斷的標準
            var timer = setInterval(function(){
                console.log(arr[i]);
                i++;
                if(i > arr.length-1){       //因為i++的原因,所以當i的值大於陣列的長度-1的時候,清除定時器
                    clearInterval(timer);
                }
            },5000);
        });
    </script>
</head>
<body ng-controller="myCtrl">
<div class="container">
    
</div>
</body>
</html>