angularjs中循环定时器的三种方法

本文主要设计定时器的三种循环,模板自配

1、$interlval实现,比较简单和原生js的setInterval比较相似

var app = angular.module('myApp',[]);
app.run(function($rootScope , $interval){
    var img=["http://hdn.xnimg.cn/photos/hdn321/20130612/2235/h_main_NNN4_e80a000007df111a.jpg" ,"http://ww2.sinaimg.cn/crop.0.0.1080.1080.1024/d773ebfajw8eum57eobkwj20u00u075w.jpg","http://h.hiphotos.baidu.com/zhidao/pic/item/3812b31bb051f81991b9d8dbdcb44aed2f73e787.jpg"]
    var i = 0;
    var timer = $interval(function(){
        if(i >= img.length){
           i = 0;
        }
        $rootScope.imgSrc = img[i++];
    },1000)
});
2、$timeout的递归调用来实现

app.run(function($rootScope,$timeout){
    var img=["http://hdn.xnimg.cn/photos/hdn321/20130612/2235/h_main_NNN4_e80a000007df111a.jpg" ,"http://ww2.sinaimg.cn/crop.0.0.1080.1080.1024/d773ebfajw8eum57eobkwj20u00u075w.jpg","http://h.hiphotos.baidu.com/zhidao/pic/item/3812b31bb051f81991b9d8dbdcb44aed2f73e787.jpg"]
    var i = 0;
    $rootScope.c = 0;
    var loop = function(){
        $timeout(function(){
            if(i >= img.length){
                i = 0;
            }
            $rootScope.imgSrc=img[i++];
            loop();
            $rootScope.c += 1;
        },2000)
    };
    loop();
})
3、$timeout借助arguments.callee来实现

app.run(function($rootScope,$timeout){
    var img=["http://hdn.xnimg.cn/photos/hdn321/20130612/2235/h_main_NNN4_e80a000007df111a.jpg" ,"http://ww2.sinaimg.cn/crop.0.0.1080.1080.1024/d773ebfajw8eum57eobkwj20u00u075w.jpg","http://h.hiphotos.baidu.com/zhidao/pic/item/3812b31bb051f81991b9d8dbdcb44aed2f73e787.jpg"]
    var i = 0;
    $rootScope.c = 0;
    var loop = function(){
        $timeout(function(){
            if(i >= img.length){
                i = 0;
            }
            $rootScope.imgSrc=img[i++];
            loop();
            $rootScope.c += 1;
        },2000)
    };
    loop();
})

你可能感兴趣的:(angularjs中循环定时器的三种方法)