Javascript function only starts when page is reloaded manually

104 views Asked by At

I have a function that works as it should, but only if the page is reloaded after landing on the specific page.

The function is a timer function that starts to tic down from 10 to 0 when the page is loaded (it should work like this).

But I land on the page and nothing happens. When I reload the page the timer starts and works...

I have tried $(document).on and window.onload = function() but with no success.

FlowRouter.route("/waitingForPlayer", {
  name: "waitingForPlayer",
  action() {
    BlazeLayout.render("iphone", { main: "waitingForPlayer" });
    console.log("first");
    window.onload = startTimer;

    function startTimer(duration, display) {
      console.log("second");
      var timer = duration,
        seconds;
      setInterval(function() {
        console.log("third");
        seconds = parseInt(timer % 60, 10);
        seconds = seconds < 10 ? "" + seconds : seconds;
        display.textContent = seconds;

        if (--timer < 0) {
          timer = duration;
        }
        if (timer == 0) {
          FlowRouter.go("readyForGame");
          document.location.reload(true);
        }
      }, 1000);
    }

    window.onload = function() {
      var fiveMinutes = 10,
        display = document.querySelector("#time");
      startTimer(fiveMinutes, display);
    };
  }
});

When the timer is = 0 the flowrouter changes view.

1

There are 1 answers

6
pbibergal On

I think the problem is that you put onload function inside the router callback. You don't need to run window.onload inside router's callback because it's Single page application router. Try to look for onComplete event of the flow-router library. I think that action is the callback for complete event of the router.

Example:

function startTimer(duration, display) {
  console.log("second");
  var timer = duration, seconds;

  setInterval(function() {
    console.log("third");
    seconds = parseInt(timer % 60, 10);
    seconds = ('0' + seconds).slice(-2);

    display.innerText = seconds;

    if (--timer < 0) {
      timer = duration;
    }
    if (timer == 0) {
      FlowRouter.go("readyForGame");
    }
  }, 1000);
}

FlowRouter.route("/waitingForPlayer", {
  name: "waitingForPlayer",
  action: function() {
    BlazeLayout.render("iphone", { main: "waitingForPlayer" });
    console.log("first");

    var fiveMinutes = 10,
      display = document.querySelector("#time");
    startTimer(fiveMinutes, display);
  }
});