简体   繁体   中英

javascript function for double call but run only once

Check the code bellow. I am calling once() function two times and the console.log() running once. But after I run the script this once() function does not run again until I refresh the html page. Now can you tell me how can I make this function as- I will always call that function two times and it will run that function only first time and it will continue without html page refresh. Any idea?

JS code:

var once = function() {
    if(once.done) return;
    console.log('Doing this once!');
    once.done = true;
};

once(); once();

You work with the same function. If you set done to true then it's not executed anymore. So it does exactly what you have programmed. The first if is stopping the next execution.

var once = function() {
    if(once.done) return;
    console.log('Doing this once!');
    once.done = true;
};

// executed
once(); 
once.done = false;
// executed
once();
// not executed
once();

First if you set done to false it will output the second result.

You are not able to call this function twice due to the condition and then setting it to true . Currently this is working as expected .

To make it work you need to set once.done= false and then call function again.

Below is working code:

 var once = function() { if (once.done) return; console.log('Doing this once!'); once.done = true; }; once(); once.done = false; once(); 

Or you can pass option as an argument, like the example shown below

var once = function(retry) {
  if (once.done && !retry) return;
  console.log('Doing this once!');
  once.done = true;
};

once();

once(true);

The status you are using needs to be new for each use. Thus if you create that function in a function and then use it as a callback it will do it once for each run of that function where it is created, but if you defined that function globally it will only work once for each reload. You decide this. I use underscore to do this so I don't have to:

 function doSomething(fn, str) { const once = _.once(fn); once(str); once(str); } doSomething(console.log, 'Hello'); doSomething(console.log, 'World'); const add = _.once(() => (console.log('adding!'),5 + 5)); console.log(add()); console.log(add()); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script> 

So what is happening is that underscore caches the result of the first run and returns the result on consecutive calls. Thus if you need the result using _.once just works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM