Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

148
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda