JavaScript实现定时器循环展示数组
本文实例为大家分享了JavaScript实现定时器循环展示数组的具体代码,供大家参考,具体内容如下
先看看效果图
流程
使用数组的slice() 方法通过条件判断截取原数组相应内容组成新数组
循环数组
let currentPage = 0 // arr:原数组 newLen:新数组需要的长度 currentPage:现在的页码 // 方法一: function loopData(arr, newLen) { let len = arr.length; let result = len - currentPage; let newArr = []; if (result > 0 && result < newLen) { newArr = [ ...arr.slice(currentPage - result, len), ...arr.slice(0, newLen - result), ]; currentPage = newLen - result; } else if (result >= newLen) { newArr = arr.slice(currentPage, currentPage + newLen); currentPage += newLen; } else { currentPage = 0; newArr = arr.slice(currentPage, currentPage + newLen); } return newArr; } // 方法二: function loopData(arr, newLen) { let len = arr.length; let newArr = []; if (currentPage === len) { // 页码等于数组长度时,从0重新开始 currentPage = 0; } if (currentPage + newLen <= len) { newArr = [...arr.slice(currentPage, currentPage + newLen)]; currentPage++; } else if (currentPage + newLen > len && currentPage < len) { newArr = [ ...arr.slice(currentPage, len), ...arr.slice(0, newLen - len + currentPage), ]; currentPage++; } return newArr; }
简单案例
<template> <div class="container"> <el-button @click="changeStatus">{{ flag ? "暂停" : "开始" }}</el-button> {{ list }} </div> </template> <script> let currentPage = 0; export default { data() { return { arr: [1, 2, 3, 4, 5, 6, 7], list: [], timer: null, flag: true, }; }, mounted() { this.start() }, destroyed() { this.timer && clearInterval(this.timer); }, methods: { changeStatus() { if (this.flag) { this.timer && clearInterval(this.timer); } else { this.start(); } this.flag = !this.flag; }, start() { this.timer = setInterval(() => { this.list = this.loopData(this.arr, 4); }, 1000); }, loopData(arr, newLen) { let len = arr.length; let newArr = []; if (currentPage === len) { currentPage = 0; } if (currentPage + newLen <= len) { newArr = [...arr.slice(currentPage, currentPage + newLen)]; currentPage++; } else if (currentPage + newLen > len && currentPage < len) { newArr = [ ...arr.slice(currentPage, len), ...arr.slice(0, newLen - len + currentPage), ]; currentPage++; } return newArr; }, }, }; </script> <style lang="scss" scoped> .container { padding: 20px; } </style>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)