Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

149
Visualizações
Node.js extremely inaccurate setTimeout

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

enter image description here

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

  • OS: windows 10
  • RAM: 16GB
  • CPU usage: 1-10%
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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:

enter image description here

This affects both setInterval and setTimeout which all non-blocking javascript timers are built on

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda