Angular.js中定时器循环的3种方法总结

2019-11-22,,,,,

本文主要设计定时器的三种循环,模板自配,下面分享给大家供大家参考,具体如下:

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相关内容感兴趣的读者可查看本站专题:《AngularJS入门与进阶教程》及《AngularJS MVC架构总结》 

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对北冥有鱼的支持。

您可能感兴趣的文章:

  • AngualrJs清除定时器遇到的坑
  • AngularJS定时器的使用与移除操作方法【interval与timeout】
  • AngularJS实现页面定时刷新
  • Angular实现的简单定时器功能示例
  • angular2组件中定时刷新并清除定时器的实例讲解

《Angular.js中定时器循环的3种方法总结.doc》

下载本文的Word格式文档,以方便收藏与打印。