cyprian
cyprian

Reputation: 497

How to call function inside itself

I have a function that I want to call again inside, after the last line finishes.

Maybe it will be more understandable if I show code.

function updateQuantity(){ 
    // further code where I change same data
    // and now I want to start function again but with remembering the input element that called it previously 
    updateQuantity(this);  // I tried it this way but it doesn't work
}

Any idea?

Upvotes: 10

Views: 26120

Answers (4)

Charles Masgalas
Charles Masgalas

Reputation: 85

You could use requestAnimationFrame(), which calls the function every frame.

HTML

<a href="#" id="link"></a>

JS

const link = document.getElementById("link");

function myFunc(value) {
      ///////////////////
     // do stuff here //
    ///////////////////
    
    // call the function again with the same parameter
    requestAnimationFrame(myFunc(value));
}

link.addEventListener("mousedown", function () {
    myFunc(link);
}, false);

Or, if you want the function to just be called twice:

HTML

<a href="#" id="link"></a>

JS

const link = document.getElementById("link");
let x = 0;

function myFunc(value) {
      ///////////////////
     // do stuff here //
    ///////////////////
    
    // call the function again but increase x so an infinite loop isn't created
    if (x < 1) {
        x++;
        myFunc(value);
    }
    else x = 0;
}

link.addEventListener("mousedown", function () {
    myFunc(link);
}, false);

Upvotes: 0

Shahzaib Sheikh
Shahzaib Sheikh

Reputation: 667

It looks like you are trying to get that DOM element in the function body.

This is a simple example: https://jsfiddle.net/c3kbu0j7/10/

HTML

<a href="#">element you want.</a>

JavaScript

$('a').on('click',function(){
    a(this);
});
var i=0;
function a(tar){
  console.log(tar);
  if(i<4){
    i++;
    a(tar);
  }
  i=0;
}

Upvotes: 0

cyprian
cyprian

Reputation: 497

The answer is simple, it is enough to use updateQuantity.call(this) inside the updateQuantity function - when we use call and add this, the function will start again and remember the input element that previously called updateQuantity.

Upvotes: 8

Uzbekjon
Uzbekjon

Reputation: 11813

From the comments to your question, it seems like you want to pass a value to your recursive method call.

function updateQuantity(val){
  // Do something with `val`
  val = val + 1;

  console.log(val);

  // And call it again with the value
  if(val < 5){
    updateQuantity(val);
  }
}

updateQuantity(1); // 2, 3, 4, 5

Upvotes: 4

Related Questions