let timeMap = new WeakMap();
document.addEventListener('mousemove', function (e) {
if (e.target.classList.contains('box')) {
clearTimeout(timeMap.get(e.target));
let newTime = setTimeout(function () {
e.target.style.backgroundColor = 'skyblue';
}, 100);
timeMap.set(e.target, newTime)
}
})
document.addEventListener('mouseout', function (e) {
if (e.target.classList.contains('box')) {
clearTimeout(timeMap.get(e.target));
e.target.style.backgroundColor = 'rosybrown';
}
})
这段代码对比单纯的在over事件中创建定时器,然后移出的时候清空有这样的好处,因为之前那样写,如果元素在dom树中被移除了,但是由于是强引用,js上关于dom对象的引用并不会被gc,这样会导致内存泄露,用warkMap可以很好的避免这一情况,它允许对每个特定的DOM元素保持独立且不泄漏内存的定时器引用。这样,即使有多个.box
元素,它们各自的延迟操作也能正确管理,互不影响。