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

118
Views
Ejecute el código Javascript solo una vez y con un solo lugar para colocar el código

Tengo una función de interceptor en la que puedo poner un código javascript (para swagger ui). Solo tengo un lugar para poner el código javascript y se volverá a ejecutar con frecuencia. Necesito agregar un observador mutante allí, y configurarlo solo una vez.

Hay muchos ejemplos de cómo hacer un método Javascript que permitirá que su código se ejecute solo una vez. Aquí hay un ejemplo popular: función en JavaScript que solo se puede llamar una vez

Pero se supone que tiene un lugar para colocar la función donde solo se llamará una vez.

¿Hay alguna manera de que mi código javascript (no necesariamente una función) solo se ejecute una vez? (¿Entonces no termino configurando un grupo de observadores mutantes?)


Para ilustrar con un ejemplo, aquí está el código de la pregunta a la que me vinculé, pero copié dos veces para mostrar que se ejecutaría muchas veces:

 var something = (function() { var executed = false; return function() { if (!executed) { executed = true; console.log("hello"); } }; })(); something(); // "do something" happens something(); // nothing happens var something = (function() { var executed = false; return function() { if (!executed) { executed = true; console.log("hello"); } }; })(); something(); // "do something" happens something(); // nothing happens

La salida de este código es:

Hola
Hola

Debido a que la función se inicializa dos veces, la llamada a console.log ocurre dos veces.

Necesito alguna forma de que mi código solo ocurra una vez, con un solo lugar para declararlo.

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

0

Para el entorno del navegador, puede usar localStorage para establecer el valor.

 // make sure to initialize with true in your main entry point, otherwise the function would not run for the first time localStorage.setItem('run-function', true); const run = localStorage.getItem('run-function'); function test() { if (run) { console.log('ran function'); // ran once, set the value to false to prevent dupes localStorage.setItem('run-function', false); } else { console.log('function already called once, exiting'); } } test();

si está en el entorno node.js, puede utilizar la variable global

 // make sure to initialize with true in your main entry point, otherwise the function would not run for the first time global.run_function = true; function test() { if (global.run_function) { console.log('ran function'); global.run_function = false; } else { console.log('function already called once, exiting'); } } test();

about 4 years ago · Juan Pablo Isaza Report

0

¿Qué pasa con el almacenamiento del valor executed en el document ... se crea una vez en la ejecución ... podría almacenarse en window (es decir, var global) pero creo que es mejor mantenerlo en el document . No estoy familiarizado con la arrogancia, pero docuument que el documento siempre debería existir. Almacenarlo en localStorage lo mantendrá más tiempo del que pueda necesitar y debe restablecerlo en cada ejecución.

 var something = (function() { return function() { if (!document.executed) { document.executed = true; console.log("hello"); } }; })(); something(); // "do something" happens something(); // nothing happens var something = (function() { return function() { if (!document.executed) { document.executed = true; console.log("hello"); } }; })(); something(); // "do something" happens something(); // nothing happens

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!