小学选手~
先看效果 :http://sandbox.runjs.cn/show/994ghu9f
- "traffic" class="wait">
2初中水平~(数据抽象
const traffic = document.getElementById("traffic"); var stateList = ["wait", "stop", "pass"]; var currentStateIndex = 0; setInterval(function(){ var state = stateList[currentStateIndex]; traffic.className = state; currentStateIndex = (currentStateIndex + 1) % stateList.length; }, 2000);
2补充--普通青年水平~~
const traffic = document.getElementById("traffic"); function start(traffic, stateList){ var currentStateIndex = 0; setInterval(function(){ var state = stateList[currentStateIndex]; traffic.className = state; currentStateIndex = (currentStateIndex + 1) % stateList.length; }, 2000); } start(traffic, ["wait", "stop", "pass"]);
3高中水平~过程抽象
const traffic = document.getElementById("traffic"); function poll(...fnList){ let stateIndex = 0; return function(...args){ let fn = fnList[stateIndex++ % fnList.length]; return fn.apply(this, args); } } function setState(state){ traffic.className = state; } let trafficStatePoll = poll(setState.bind(null, "wait"), setState.bind(null, "stop"), setState.bind(null, "pass")); setInterval(trafficStatePoll, 2000);
4 大学版本~各种新特性哈哈
const traffic = document.getElementById("traffic"); function wait(time){ return new Promise(resolve => setTimeout(resolve, time)); } function setState(state){ traffic.className = state; } function reset(){ Promise.resolve() .then(setState.bind(null, "wait")) .then(wait.bind(null, 1000)) .then(setState.bind(null, "stop")) .then(wait.bind(null, 2000)) .then(setState.bind(null, "pass")) .then(wait.bind(null, 3000)) .then(reset); } reset();
5 宇宙版本……现在有点看不懂 留在以后再看
const trafficEl = document.getElementById("traffic"); function TrafficProtocol(el, reset){ this.subject = el; this.autoReset = reset; this.stateList = []; } TrafficProtocol.prototype.putState = function(fn){ this.stateList.push(fn); } TrafficProtocol.prototype.reset = function(){ let subject = this.subject; this.statePromise = Promise.resolve(); this.stateList.forEach((stateFn) => { this.statePromise = this.statePromise.then(()=>{ return new Promise(resolve => { stateFn(subject, resolve); }); }); }); if(this.autoReset){ this.statePromise.then(this.reset.bind(this)); } } TrafficProtocol.prototype.start = function(){ this.reset(); } var traffic = new TrafficProtocol(trafficEl, true); traffic.putState(function(subject, next){ subject.className = "wait"; setTimeout(next, 1000); }); traffic.putState(function(subject, next){ subject.className = "stop"; setTimeout(next, 2000); }); traffic.putState(function(subject, next){ subject.className = "pass"; setTimeout(next, 3000); }); traffic.start();
参考:http://mp.weixin.qq.com/s?__biz=MzAxODE2MjM1MA==&mid=2651551635&idx=1&sn=a7d6e09a94ef854a94ed578a9de70015&chksm=8025a052b752294443a3a89745ded0cc158bcba1fb6e5af1fa2c223f379341da3b58c8fe00a9&mpshare=1&scene=23&srcid=0108Rg5m1KroA9GpzeTWQBMh#rd
http://www.cnblogs.com/yunfeifei/p/4453690.html