-
現(xiàn)象
windows 和 linux 系統(tǒng)網(wǎng)頁掛載svg文件棋弥,出現(xiàn)cpu占比逐步增加的情況杖爽,時(shí)間過長(zhǎng)后會(huì)發(fā)現(xiàn)頁面瀏覽操作變得卡頓,鼠標(biāo)事件響應(yīng)變得很慢空免。最后可能導(dǎo)致系統(tǒng)崩潰空另。
-
原因
因?yàn)榇a是由外包人員編寫,因此找錯(cuò)的過程變得比較復(fù)雜蹋砚,最終定位到以下的代碼:
const timeLine = sureMinTime(); timeLine > 0 && setInterval(() => { lineChartT(); }, timeLine * 1000); function sureMinTime() { let node = document.rootElement || document.getElementsByTagName("svg")[0]; let nodeAction = node.querySelectorAll("g[TypeName = 'chartT']"); let arr = []; nodeAction.forEach(e => { //... arr.push(((end - start) / Math.max(...arrMiddle)).toFixed(3) - 0); }) return Math.min(...arr) || 0; }
問題出在
return Math.min(...arr) || 0;
這句代碼上扼菠。當(dāng)arr
的數(shù)組長(zhǎng)度為0時(shí),Math.min(...[])
返回的結(jié)果是Infinity
坝咐。而Infinity || 0
返回的也是Infinity
循榆。Infinity > 0
返回true
, 且Infinity * 1000
依舊是Infinity(正無窮大)
。setTimeout/setInterval delay數(shù)值過大問題,如果 delay 是 Infinity 值墨坚,非數(shù)字(NaN)值或負(fù)值秧饮,則將超時(shí)設(shè)置為零,因此導(dǎo)致上面的定時(shí)器無延遲立即執(zhí)行(這個(gè)是問題的根本原因)。
-
修改
function sureMinTime() { let node = document.rootElement || document.getElementsByTagName("svg")[0]; let nodeAction = node.querySelectorAll("g[TypeName = 'chartT']"); let arr = []; nodeAction.forEach(e => { //... arr.push(((end - start) / Math.max(...arrMiddle)).toFixed(3) - 0); }) if (arr.length && Math.min(...arr) > 0) { return Math.min(...arr) || 0; } else { return 0; } }