-4

I am trying to make a script that will run a different function every time the button is clicked in a ordered way. So for example when the button is clicked it will run the tick1 function first, then when pressed again it will run the tick2 function. This is my attempt but it will only run the tick1 function. Many thanks, Simon

<script>
var trafficktick = 1;
function tick() {
    if (trafficktick = 1) {
        tick1()
        var traffictick =  trafficktick + 1;
    } else if (trafficktick = 2) {
        tick2()
        var traffictick = trafficktick + 1;
    } else {
        var trafficktick = 1;
    }
} 
</script>
Craicerjack
  • 6,203
  • 2
  • 31
  • 39
ReaP
  • 5
  • 2

3 Answers3

1

In the if condition use === and not =

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
fistuks
  • 469
  • 3
  • 5
1

Multiple errors where done :

  1. You were using = (assign a value) instead of === (comparaison)
  2. You miswrote trafficktick
  3. Instead of doing var trafficktick = trafficktick + 1;. Simply do trafficktick++;

var trafficktick = 1;

function tick() {
  if (trafficktick === 1) {
    //tick1();
    console.log("Call tick1");
    trafficktick++;
  } else if (trafficktick === 2) {
    //tick2();
     console.log("Call tick2");
    trafficktick++;
  } else {
    trafficktick = 1;
  }
}
<button onclick="tick()">Click me</button>
Weedoze
  • 13,683
  • 1
  • 33
  • 63
0

There's some errors in your JavaScript, try something like this:

<script>
    var trafficktick = 1; // Use var only here

    function tick() {

        // Use '==' or '===' depending on your logic operation to 
        // compare equality
        if (trafficktick == 1) { 

            // You want that? You can comment this call and call
            // it outside from an element (for example)
            tick1(); 
            traffictick ++; // Only '++' and no 'var' 

        } else if (trafficktick == 2) {

            tick2();
            traffictick ++; // Only '++' and no 'var'

        } else {

            trafficktick = 1; // No 'var'

        }
    } 
</script>
RPichioli
  • 3,245
  • 2
  • 25
  • 29
  • I still get the same problem, it stays only runs tick1 and never tick2 :l – ReaP Oct 07 '16 at 13:39
  • Nvm i figured it out thanks :D – ReaP Oct 07 '16 at 13:40
  • @ReaP If you can not get it working you can try my working snipper answer – Weedoze Oct 07 '16 at 13:50
  • @ReaP your tick1() and tick2() calls the tick() function? The tick() function only route the calls based on the count and sum it (and by consequence you'll be in another condition in the next time) or set 1 again. Take care about the way you are working with the calls, we don't have it in this snippet. – RPichioli Oct 07 '16 at 13:53