Reputation: 21
I have a variable named session that i am incrementing up or down when a button is clicked. Then I have a timer that takes the parameter of the session variable that starts when I click the start button but my session variable is still the original value that it was initialized. How can I update the value to be able to use it in real time?
jsfiddle - https://jsfiddle.net/0u24qr47/2/
Thanks.
HTML
<h1>Adjust Work Time</h1>
<div id="workTime"></div>
<button class="btn btn-success" id="workMinus">-</button>
<button class="btn btn-success" id="workPlus">+</button>
<h1>Break Time</h1>
<div id="breakLength"></div>
<button class="btn btn-success" id="breakMinus">-</button>
<button class="btn btn-success" id="breakPlus">+</button>
<h1>Clock</h1>
<div><span class="time"></span>
</div>
<button class="btn btn-success start" id="start">start</button>
Javascript
$(document).ready(function() {
var session = 25;
var breaks = 5;
var workTime = document.getElementById('workTime');
var breakLength = document.getElementById('breakLength');
//update display//
workTime.innerHTML = session;
breakLength.innerHTML = breaks;
//functions for updating variables//
function wMinus() {
session--;
workTime.innerHTML = session;
}
function wPlus() {
session++;
workTime.innerHTML = session;
}
function bMinus() {
breaks--;
breakLength.innerHTML = breaks;
}
function bPlus() {
breaks++;
breakLength.innerHTML = breaks;
}
//update variables when clicked//
$("#breakMinus").click(function() {
bMinus();
});
$("#breakPlus").click(function() {
bPlus();
});
$("#workMinus").click(function() {
wMinus();
});
$("#workPlus").click(function() {
wPlus();
});
window.onload = function () {
console.log("in onload" + session);
var display = document.querySelector('.time'),
timer = new CountDownTimer(session),
timeObj = CountDownTimer.parse(session);
format(timeObj.minutes, timeObj.seconds);
timer.onTick(format);
//click//
document.querySelector('#start').addEventListener('click', function() {
timer.start();
});
function format(minutes, seconds) {
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ':' + seconds;
}
};
});
Upvotes: 1
Views: 84
Reputation: 12214
Parameters are passed by value, not by reference. The value of the variable session
is passed to the constructor of the timer when this line is executed (when your page loads):
timer = new CountDownTimer(session),
You need to create the timer when the 'start' button is clicked and pass it the value of session
then, not when the page loads.
Upvotes: 1