Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

121
Views
¿Cómo evito que se ejecute el tiempo de espera si la condición cambia o se actualiza?

código:

 const isEnd = false; // Whenever event triggers the value will be false. if (isEnd) { console.log('Manual End') } else { setTimeout(() => { console.log('Automatic End') }, 30000); }

Tema:

  • Este es un evento, por lo que cuando el evento se activa, el valor isEnd será false y cuando el evento se activa, tiene 30 segundos para actualizar el valor a true .
  • El valor isEnd se puede cambiar a true , en cualquier momento por el usuario/yo en la aplicación en ejecución o sin reiniciar.
  • Si los valores de isEnd cambian a true en un tiempo determinado (30 segundos), quiero registrar el final manual y eliminar setTimeout y no registrar nada dentro de la función setTimeout.

Probé hasta ahora:

  • intentado si/si no, cambiar, mientras, hacer mientras.
  • Traté de borrar el tiempo de espera y de muchas maneras diferentes, pero no puedo eliminar el tiempo de espera establecido.
 import { setTimeout as wait } from 'node:timers/promises'; let timerId; switch (isEnded) { case true: console.log('Manual Ended'); clearTimeout(timerId); break; case false: clearTimeout(timerId); timerId = wait(30000).then(() => { console.log('Automatic Ended'); }); break; }

exceptuado:

  • si la condición actualiza el registro manual End
  • si la condición no cambia, solo debe registrar Automatic End
  • debe registrar solo uno de los dos registros.
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

en lugar de intentar desencadenar cambios en el valor de isEnd , puede probar un enfoque diferente,

puede borrar directamente clearTimeOut siempre que usted o el usuario cambien el valor de isEnd

por ejemplo en lugar de hacer esto

 const isEnd = false let timerId; buttn.addEventListener("click", () => { isEnd = true }) if (isEnd) { console.log('Manual End') clearTimeOut(timerId) } else { timerId = setTimeout(() => { console.log('Automatic End') }, 30000); }

hacer esto

 let timerId = setTimeout(automaticEnd, 30000); // when the user make a manual break cancelButton.addEventListener("click", () => { manualEnd() }) function automaticEnd() { console.log('Automatic End') } function manualEnd() { clearTimeOut(timerId) console.log("manualEnd") }
about 4 years ago · Juan Pablo Isaza Report

0

Podría probar un enfoque de alguna manera más complejo pero interesante y elegante, usando una estructura de objeto para su condición isEnd y usando getters y setters de objetos para suscribirse a un oyente personalizado para cambios de propiedades de objetos:

Esto funciona perfectamente en la consola del navegador (puede iniciar el fragmento), también debería funcionar en Node:

 // Object of your condition const isEnd = { _value: false, // this is the value of the condition valueListener: function(val) {}, // defining a generic listener // getter get value() { return this._value; }, // setter set value(val) { this._value = val; this.valueListener(val); // when changing the value, the function valueListener is called with the new value set }, // method to pass an actual listener function to valueListener property listenTo: function(listener) { this.valueListener = listener; } }; console.log("START: isEnd has a value of: " + isEnd.value); // timer of 20 seconds const timer = setTimeout(() => { console.log('Timer expired'); }, 20000) // you subscribe to the isEnd.value change, passing an actual listener function // this function should contain the logic to execute // based on the new condition value // (like clearing the timer) isEnd.listenTo(function(val) { console.log('new value for isEnd is now: ' + val); if (val === true) { if (timer) { clearTimeout(timer); console.log('timer cleared!'); } } if (val === false) { console.log('HEY... false again!'); } }) // timer of 5 seconds that simulates // the condition changing after 5 seconds setTimeout(function() { isEnd.value = true; }, 5000) // timer of 10 seconds that simulates // the condition changing after // another 5 seconds setTimeout(function() { isEnd.value = false; }, 10000)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!