-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
/**start context demo */
let contextMap = {}; // 上下文map
let contextId = 0; // 当前上下文id
const useContext = () => contextMap[contextId]
function run(cb) {
contextId++; // 创建新的上下文id
contextMap[contextId] = contextMap[contextId] || {}; // 创建新的上下文
cb();
}
const origin = setTimeout;
setTimeout = (cb, delay) => {
const id = contextId; // 闭包保存当前上下文id
return origin(() => {
contextId = id;
cb();
}, delay);
};
/**end context demo */
function foo(id, delay) {
const ctx = useContext();
ctx.id = id;
setTimeout(bar, delay); // 记录当前的contextId
}
function bar() {
const ctx = useContext();
console.log(ctx.id);
}
// Test
run(() => foo(1, 700));
run(() => foo(2, 1000));
run(() => foo(3, 1500));
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels