Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

111
Visualizações
Run Javascript code only once, and with only one spot to put the code

I have an interceptor function that I can put some javascript code into (for swagger ui). I only have one place to put in javascript code and it will be re-run frequently. I need to add a mutating observer in there, and have it only be setup one time.

There are many examples of how to do a Javascript method that will allow your code to be only run once. Here is a popular example: Function in JavaScript that can be called only once

But it assumes that you have somewhere to put the function where it will only be called once.

Is there a way to have my javascript code (not necessarily a function) only be run once? (So I don't end up setting up a bunch of mutating observers?)


To illustrate with an example, here is the code from the question I linked to, but copied in twice to show that it would be run many times:

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

The output of this code is:

hello
hello

Because the function is initalized twice, the call to console.log happens twice.

I need some way to have my code only happen once, with only one place to declare it.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

For browser environment, you can use localStorage to set the value.

// 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();

if you're on node.js environment you can make use of the global variable

// 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 Relatório

0

What about storing executed value in document ... it is created once at execution ... it could be stored in window (i.e. global var) but I think it is better to be kept in document. I'm not familiar with swagger but docuument should always exits I think. Storing it in localStorage will keep it longer than you may need and you should reset it on each run.

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda