Created
March 25, 2016 07:53
-
-
Save maolion/76e96546e465b74604ff to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <html> | |
| <head> | |
| </head> | |
| <body> | |
| <script> | |
| var EventLoop = (function () { | |
| //任性的实现 私有变量 访问控制 | |
| var fuck = (function(){ | |
| var data = []; | |
| return { | |
| create: function(instance) { | |
| var d = {}; | |
| data.push([instance, d]) | |
| return d; | |
| }, | |
| get: function (instance) { | |
| for (var item of data) { | |
| if (item[0] === instance) { | |
| return item[1]; | |
| } | |
| } | |
| }, | |
| remove: function(instance) { | |
| var n = 0; | |
| for (var i = 0, l = data.length; i < l; i++) { | |
| if (data[i][0] !== instance) { | |
| data[n++] = data[i]; | |
| } | |
| } | |
| } | |
| } | |
| })(); | |
| function EventLoop() { | |
| var data = fuck.create(this); | |
| data.list = []; | |
| }; | |
| //api | |
| EventLoop.prototype.push = function(work) { | |
| getList.call(this).push(work); | |
| }; | |
| EventLoop.prototype.run = function () { | |
| var list = getList.call(this); | |
| var work = list.shift(); | |
| var _this = this; | |
| setTimeout(function() { | |
| work(); | |
| if (list.length) { | |
| _this.run(); | |
| } | |
| }, 100) | |
| } | |
| return EventLoop; | |
| //private method | |
| function getList() { | |
| return fuck.get(this).list; | |
| } | |
| })(); | |
| var eventLoop = new EventLoop(); | |
| var a = 0; | |
| eventLoop.push((function() { | |
| var endTime = Date.now() + 1000; | |
| return function (){ | |
| if (Date.now() >= endTime) { | |
| a = 10; | |
| console.log("跑到1000毫秒号"); | |
| } else { | |
| eventLoop.push(arguments.callee); | |
| } | |
| } | |
| })()); | |
| eventLoop.push((function() { | |
| var endTime = Date.now() + 1000; | |
| return function () { | |
| if (a == 10) { | |
| //我要做这件事 | |
| } else { | |
| console.error('我没有去做那件事'); | |
| } | |
| } | |
| })()); | |
| eventLoop.run(); | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment