Danny Huang
Danny Huang

Reputation: 27

Switching between two setInterval functions

Question: Hi, I'm working on a pomodoro JS problem. I'm having problem with switching from sessionTime to breakTime when sessionTime has countdown to zero.

Possible Solutions: I tried to methods (startPomodoro(), startPomodoroTwo()) but neither work.

var countdown;

var model = {
  sessionTime: { seconds: 10, isFinished: false},
  breakTime: { seconds: 5, isFinished: false},

  timer: function(obj){
    console.log(obj.seconds);
    var self = this;
    countdown = setInterval(function() {
      obj.seconds--;
      console.log(obj.seconds);
      if(obj.seconds <= 0){
        obj.isFinished = true;
        clearInterval(countdown);
        return;
      }
    },500);
  },

  startPomodoro: function(){
    this.timer(this.sessionTime)
    this.timer(this.breakTime)
  },

  startPomodoroTwo: function(){
    if(this.sessionTime.isFinished === false){
    this.timer(this.sessionTime)
  } else if (this.breakTime.isFinished === false && this.sessionTime.isFinished === true){
    this.timer(this.breakTime)
  } else {
    console.log("Finish Pomo");
    }
  }
}
  1. startPomodoro(), it would just count down sessionTime, and breakTime simultaneously

  2. startPomodoroTwo(), this works but i need to execute the function three times which is not that i want.

Upvotes: 0

Views: 383

Answers (1)

000
000

Reputation: 27247

Try creating an array for activities:

var activities = [
  {name: 'session', duration: 10},
  {name: 'break', duration: 5}
];
var currentActivity = 0;

then switch activities when the timer is done.

function startActivity() {
  console.log(activities[currentActivity]);
  var duration = activities[currentActivity].duration;
  var timer = setInterval(function () {
    duration--;
    if (!duration) {
      currentActivity = (currentActivity + 1) % activities.length;
      clearInterval(timer);
      startActivity();
    }
  }, 1000);
}

Try to not modify the activity objects. Your code mutates the reference objects, which means you'll have to reset the seconds back to 10 or 5 when the activity is done.

Upvotes: 1

Related Questions