Neel Bhasin
Neel Bhasin

Reputation: 759

javascript function calling with timer not working properly

i have write this code for perform simple action but not working at all

<script type="text/javascript">
    var a = 10;

    function add() {
        window.setInterval(a2, 10000);

            alert(a);

    }
    function a2() {

        a = a + 2;
    }


</script>

this alert in only returning value 10 only one time. how to achieve this working through timing and looping?

Upvotes: 0

Views: 103

Answers (3)

Enthusiasmus
Enthusiasmus

Reputation: 323

Try this instead:

  var a = 10;

  window.setInterval(add, 1000);

  function add() {
      alert(a);
      a = a + 2;
  }

Upvotes: 0

AlecTMH
AlecTMH

Reputation: 2725

Your alert instruction is out of the interval, try the code below:

<script type="text/javascript">
    var a = 10;

    function add() {
        window.setInterval(a2, 10000);
   }
   function a2() {
        a = a + 2;
        alert(a);
   }

</script>

Upvotes: 2

Teemu
Teemu

Reputation: 23396

If you want more alerts, you need to put alert() in the timed function itself. Execution won't return to add() from a2().

function a2() {
    a = a + 2;
    alert(a);
}

Upvotes: 2

Related Questions