Function in JavaScript That Can Be Called Only Once

Function in JavaScript that can be called only once

If by "won't be executed" you mean "will do nothing when called more than once", you can create a closure:

var something = (function() {
var executed = false;
return function() {
if (!executed) {
executed = true;
// do something
}
};
})();

something(); // "do something" happens
something(); // nothing happens

In answer to a comment by @Vladloffe (now deleted): With a global variable, other code could reset the value of the "executed" flag (whatever name you pick for it). With a closure, other code has no way to do that, either accidentally or deliberately.

As other answers here point out, several libraries (such as Underscore and Ramda) have a little utility function (typically named once()[*]) that accepts a function as an argument and returns another function that calls the supplied function exactly once, regardless of how many times the returned function is called. The returned function also caches the value first returned by the supplied function and returns that on subsequent calls.

However, if you aren't using such a third-party library, but still want a utility function (rather than the nonce solution I offered above), it's easy enough to implement. The nicest version I've seen is this one posted by David Walsh:

function once(fn, context) { 
var result;
return function() {
if (fn) {
result = fn.apply(context || this, arguments);
fn = null;
}
return result;
};
}

I would be inclined to change fn = null; to fn = context = null;. There's no reason for the closure to maintain a reference to context once fn has been called.

Usage:

function something() { /* do something */ }
var one_something = once(something);

one_something(); // "do something" happens
one_something(); // nothing happens

[*] Be aware, though, that other libraries, such as this Drupal extension to jQuery, may have a function named once() that does something quite different.

Run Function only once in Javascript

Try not to use timeouts, they invite misery and suffering. This is a simple example, I use jquery for attaching the events but the function is independent of jquery. The key thing is using the object, the anonymous function in this case, to track state.

<button id="testButton">
test
</button>

$("#testButton").click(function() {
if (null == this.ran) {
console.log("do something");
this.ran = true;
}
})

javascript function for double call but run only once

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

js only - run a function only once

If you call a function just once, why do you need the function at all?

const snapshot = await firebase.firestore().collection('riders').get()
// Do my thing with the data, etc.
// console.log(snapshot.docs.map(doc => doc.data()));

This top level await only works in modules, and it blocks all depending modules to load. If that is not necessary (they don't depend on the data), or if you don't want write a module, you can wrap the code in an async IIFE, and store the returned promise in a variable:

 const dataPromise =  (async function() {
//...
return data;
})();

While the data is loading, you might want to show some loading icon or so. That can easily be done with the following hook:

 function usePromise(p) {
const [state, setState] = useState(null);
useEffect(() => { p.then(setState); }, []);
return state;
}

// Inside a component:
const data = usePromise(dataPromise);
if(data === null)
return <Loading />;

// show data

Call js function only once in javascript

Use a flag variable

var myflag = false;
function view(str) {
$.ajax({
type : "POST",
url : '<?php echo base_url()?>index.php/main/' + str + '/',

success : function(output_string) {
if (!myflag) {
view(str);
}
myflag = true;
}
});
}

JavaScript function called only once instead of every time

No need to clone the node etc ... just set the value to '';

file.value = '';

see working snippet

document.getElementById("myFile").addEventListener('change', function() {  if (this.files[0].size > 2*1024*1024) {    alert('Max file size is 2 MB');    this.value='';  }});
<form action="?" method="post">    <input type="file" id="myFile" name="myFile" />    <input type="submit" value="upload" /></form>


Related Topics



Leave a reply



Submit