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:
isEnd será false y cuando el evento se activa, tiene 30 segundos para actualizar el valor a true .isEnd se puede cambiar a true , en cualquier momento por el usuario/yo en la aplicación en ejecución o sin reiniciar.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:
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:
manual EndAutomatic Enden 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") }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)