工作中会遇到低版本安卓设备调用setTimeout不生效,既不会报错,里面的函数也不会执行,这里po一个解决办法,如果不执行则执行安卓自己封装的原生的setTimeout方法:sdk.setTimeout。
注明:此方法为我们老大所写,放在这里惠存一下。
基本方案
/*******/
(function(window){
Promise.race([
new Promise((resolve)=>{
window.setTimeout(()=>{
resolve(window.setTimeout)
},0)
}),
new Promise((resolve)=>{
sdk.setTimeout(()=>{
resolve(sdk.setTimeout.bind(sdk))
},100)
})
]).then((fn)=>{
window.setTimeout = fn
})
})(window) window.setTimeout(()=>{
cosole.log('hello world')
},1000) 进阶方案
/*******/ (function(window){
const st = window.setTimeout.bind(window)
let callList = []
window.setTimeout = function(cb, duration){
callList.push(cb)
return st(cb, duration)
}
Promise.race([
new Promise((resolve)=>{
window.setTimeout(()=>{
resolve(()=>{
return st
})
},0)
}),
new Promise((resolve)=>{
sdk.setTimeout(()=>{
resolve(()=>{
callList.forEach(fn=>{
sdk.setTimeout(fn, duration)
})
window.clearTimeout = sdk.clearTimeout.bind(sdk)
return sdk.setTimeout.bind(sdk)
})
},100)
})
]).then((fn)=>{
window.setTimeout = fn()
})
})(window)