Last active
October 10, 2016 07:37
-
-
Save alsotang/619eb408707170af9290 to your computer and use it in GitHub Desktop.
alock
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
| // alock 是用来控制某个函数的回调一定只执行最新的库 | |
| var alock = { | |
| count: 0, | |
| locks: { | |
| }, | |
| set: function (lockName, val) { | |
| if (!val) { | |
| val = ++this.count | |
| } | |
| this.locks[lockName] = val; | |
| return val; | |
| }, | |
| get: function (lockName) { | |
| return this.locks[lockName] | |
| }, | |
| check: function (lockName, val) { | |
| if (this.locks[lockName] == val) { | |
| return true; | |
| } | |
| return false; | |
| } | |
| } | |
| // 某个被触发之后,返回时间不确定的函数 | |
| var asyncFn = function (callback) { | |
| var timeout = ~~(Math.random() * 1000 + 100) // 毫秒的整数时间 | |
| console.log('timeout: ' + timeout) | |
| setTimeout(function () { | |
| callback(null, timeout) | |
| }, timeout) | |
| } | |
| // 在不同的时间,分别发起5个async请求,他们的执行时间都不确定,但一定只执行最后发出的那个 | |
| for (var i = 0; i < 5; i++) { | |
| setTimeout(function () { | |
| var lock = alock.set('my_func') // 为 asyncFn 设置一个名称叫 my_func | |
| asyncFn(function (err, value) { | |
| if (!alock.check('my_func', lock)) { // 检查这个回调是否对应 my_func 最后一次的调用 | |
| console.log('give up:', value) | |
| return | |
| } | |
| // console.log(alock.locks, 'my_lock_value:', lock) | |
| console.log('finally execute: ' + value) | |
| }) | |
| }, Math.random() * 100) | |
| } | |
| /* | |
| 执行结果: | |
| timeout: 962 | |
| timeout: 787 | |
| timeout: 184 | |
| timeout: 933 | |
| timeout: 110 | |
| finally execute: 110 | |
| give up: 184 | |
| give up: 787 | |
| give up: 962 | |
| give up: 933 | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment