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

218
Views
javascript detiene setTimeout después de contener el objeto eliminado o sobrescrito

Me gustaría detener un temporizador después de eliminar la variable que contiene la función que la ejecutó.

Lo siguiente funciona pero requiere un paso adicional:

 foo = (function() { function doSomething() { console.log('I am running ') timer1 = setTimeout(doSomething, 2000) } doSomething() console.log('timer is #' + (bob)) return { stopTimer: function() { clearTimeout(timer1) return true } } })() // // let it run a while.. // // later, stop it .. this works but is an extra step foo.stopTimer() // no more logs .. success

Es decir, detiene el temporizador. Sin embargo, el OBJETIVO REAL es solo hacer esto:

 foo = <new code like a new version overwriting the existing one> -- or less desirably -- foo = null

Y haz que se detengan los temporizadores. ¿Es posible? y si lo es, ¿cómo?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Es posible , pero solo mediante el uso de trucos, lo que recomiendo encarecidamente no hacer, porque ofuscan en gran medida la intención del código.

Al poner foo en el objeto global (o with with - por favor no lo haga), puede convertirlo en getter/setter, donde el setter, cuando se invoque, llamará a stopTimer .

 let timer1; function doSomething() { console.log('I am running ') timer1 = setTimeout(doSomething, 1000) } doSomething(); Object.defineProperty( window, 'foo', { set(newArg) { clearTimeout(timer1); // delete this setter delete window.foo window.foo = newArg; }, configurable: true } ); button.onclick = () => { console.log('stopping timer'); foo = null; console.log('new value of window.foo:', foo); };
 <button id="button">stop</button>

Un enfoque más sensato, si su objetivo es no tener que tener una línea que llame a foo.stopTimer y también tener una línea que cree un nuevo temporizador (o algo así), sería crear un método que detenga el temporizador y cree el nuevo deseado de una vez, como

 // callback interval foo.makeNewTimer(() => console.log('new'), 1000);
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!