Initially, I had a piece of code to perform certain operations periodically. Though I encountered weird performance and timing issues.
I isolated the main loop in its own script below
let sleepTime = 50 //milliseconds
var sleep = (ms) => new Promise(res => setTimeout(res, ms))
let state = {
stopCalled: false,
countLoops: 0,
lastLoopTime: 0,
loopDuration: 0,
badLoops: [],
badSleeps: []
}
let data = [1, 2, 3, 5, 1, 1, 1, 5, 1, 3, 1, 5, 4]
async function startLoop() {
//necessary for first loopDuration
state.lastLoopTime = Date.now() - 50
while (true) {
if (state.stopCalled) return
state.countLoops++
state.loopDuration = Date.now() - state.lastLoopTime
state.lastLoopTime = Date.now()
if (state.loopDuration > 100) {
state.badLoops.push(state.loopDuration)
console.log(`Bad loop duration: ${state.loopDuration}`)
}
//do some random work
let rand = randomInteger(1, 7)
for (let i = 0; i <data.length; i++) {
if (data[i] === rand) continue
data[i] = randomInteger(1, 7)
}
let initialTime = Date.now()
await sleep(sleepTime)
let actualSleepDuration = Date.now() - initialTime
//sleep duration should be <=50 milliseconds
if (actualSleepDuration > 100) {
state.badSleeps.push(actualSleepDuration)
console.log(`Bad sleep duration: ${actualSleepDuration}`)
}
}
}
function randomInteger(min, max) {
return Math.round((max - min) * Math.random()) + min
}
A summary of what the code does: After startLoop is manually called, it should run the loop periodically every 50ms I expected a +/-5ms inaccuracies which is ok.
However, the sleep function/ setTimeout function gets wildly inaccurate upto 1 whole minute especially after running for along time
I understand setTimeout, is more accurate if there is no blocking code, in this case, this is the only script running, which doesn't make sense to why there is so much lag.
Is there a more accurate way to run a function?
Done two tests From:
one from Electron 17.0.1
another from Node JS 17.5.0 REPL with .load file.js
After alot of testing, found out that chrome throttles background tabs/windows from Chrome 88 ,which is great for websites on laptops to save on power
But really bad for electron apps (use Chromium engine), that should not be throttled.
To solve this you should change backgroundThrottling to false, which by default is true
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
backgroundThrottling: false,
}
})
An excerpt from the throttling doc:
This affects both setInterval and setTimeout which all non-blocking javascript timers are built on