I am trying to validate that the time is past the current time in my "if" statement. This is a javascript file.
addNewTodoSave() {
var self = this;
if (this.validateFields()) {
var todos = State.getState().todos;
if (!todos) {
todos = [];
}
var date = moment(self.$el.find('.add-todo .date-input').val());
var time;
if (moment(self.$el.find('.add-todo .todo-time input').val(), 'hh:mm A').isValid()) {
time = moment(self.$el.find('.add-todo .todo-time input').val(), 'hh:mm A').format('HH:mm:ss');
} else if (moment(self.$el.find('.add-todo .todo-time input').val(), 'HH:mm').isValid()) {
time = moment(self.$el.find('.add-todo .todo-time input').val(), 'HH:mm').format('HH:mm:ss');
} else {
time = '';
}
}
}
Related
I'm new to JavaScript and I made a simple stopwatch constructor:
function Stopwatch() {
var started = false;
var elapsed;
var start;
d = new Date();
this.duration = function() {
if (started) {
throw "Stopwatch is still running"
} else {
return (elapsed);
}
}
this.start = function() {
if (started) {
throw "Stopwatch has already started";
} else {
start = d.getTime();
started = true;
}
}
this.stop = function() {
if (!started) {
throw "Stopwatch hasn't started";
} else {
elapsed = d.getTime() - start;
started = false;
}
}
this.reset = function() {
started = false;
elapsed = 0;
}
}
let sw = new Stopwatch();
sw.start();
setTimeout(function () {
sw.stop();
console.log(sw.duration());
}, 500);
The logic of the errors works fine, but whenever I call sw.duration(), it always returns zero, and I'm not sure why that is since I'm using var instead of let. Please let me know.
You're calling new Date only once, at the start of the constructor. Use Date.now instead (to get a number, to avoid having to call .getTime), and call it not only when you need to assign to start, but also in .stop, to get elapsed.
function Stopwatch() {
var started = false;
var elapsed;
var start;
this.duration = function() {
if (started) {
throw "Stopwatch is still running"
} else {
return (elapsed);
}
}
this.start = function() {
if (started) {
throw "Stopwatch has already started";
} else {
start = Date.now();
started = true;
}
}
this.stop = function() {
if (!started) {
throw "Stopwatch hasn't started";
} else {
elapsed = Date.now() - start;
started = false;
}
}
this.reset = function() {
started = false;
elapsed = 0;
}
}
let sw = new Stopwatch();
sw.start();
setTimeout(() => {
sw.stop();
console.log(sw.duration());
}, 500);
I'm creating a countdown of 10 seconds, and at the end, some functions triggers.
These functions that recall the countdown function to start again. However, when it's called again, the bar is still full, resulting in a loop.
Here's the countdown function.
function LoadTime() {
firebase.auth().onAuthStateChanged(User => {
if(User) {
var RemainTime = 10;
var DownTime = setInterval(function(){
document.getElementById("progressBar").value = 10 - --RemainTime;
if(RemainTime <= 0)
clearInterval(DownTime);
if (RemainTime == 0){
storewager();
if (Roulette.bet == 1) {
RouOutcome();
}
else {
LoadTime();
}
}
},1000);
} else {
alert("please login");
}
});
}
I want this functions to reset the progress bar each time it's triggered. Been stuck on this for a while, so any help is much appreciated.
EDIT:
Here's the tree of the functions.
Page load --> LoadTime --> (end of countdown) --> (Outcome process) --> RouOutcome() --> LoadTime().
Seems to be when LoadTime is triggered when it's already finished once, it seems to run the process multiple times. It may be to do with the alert boxes causing issues for the countdown.
Been stuck on this for hours, so any help is much appreciated.
EDIT 2:
Here's are the relevant functions in the correct order. This is assuming the users picks a bet option, and enters a bet. I'm trying to create roulette. Is it possible that the issue could be with the alerts?
function LoadTime() {
Roulette.load = 1;
CoinFlip.load = 0;
document.getElementById().style.visibility = "hidden";
firebase.auth().onAuthStateChanged(User => {
if(User) {
console.log("user is logged in");
Roulette.choice = 0;
var RemainTime = 15;
var DownTime = setInterval(function(){
document.getElementById("progressBar").value = 15 - --RemainTime;
if(RemainTime <= 0)
clearInterval(DownTime);
if (RemainTime == 0){
storewager();
if (Roulette.bet == 1) {
RouOutcome();
}
else {
LoadTime();
}
}
},1000);
} else {
alert("please login");
}
});
}
function storewager(){
var UserID = firebase.auth().currentUser.uid;
firebase.database().ref("Users").child(UserID).child("coinbet").set(0);
var coinwager = document.getElementById("coininput").value;
if (coinwager > 0) {
Roulette.bet = 1;
var balref = firebase.database().ref("Users").child(UserID).child("coinbet");
firebase.database().ref("Users").child(UserID).child("coinbet").set(coinwager);
var coinref = firebase.database().ref();
coinref.child("coinbet").set(coinwager);
BalVer();
}
else {
alert("No bet was placed");
Roulette.bet = 0;
LoadTime();
}
}
function BalVer(){
var UserID = firebase.auth().currentUser.uid;
var dbRoot = firebase.database().ref("Users").child(UserID);
dbRoot.once("value", snap => {
var cData = snap.val();
var cBet = cData.coinbet;
var uBal = cData.userbalance;
var BalUp = uBal-cBet;
if (BalUp < 0) {
alert("You do not have enough balance")
var BetWipe = firebase.database().ref("Users").child(UserID).child("coinbet").set(0);
}
else {
changeuserbal();
}
});
}
function changeuserbal(coinwager){
var UserID = firebase.auth().currentUser.uid;
var dbRoot = firebase.database().ref("Users").child(UserID);
dbRoot.once("value", snap => {
var cData = snap.val();
var cBet = cData.coinbet;
var uBal = cData.userbalance;
var BalUp = uBal-cBet;
firebase.database().ref("Users").child(UserID).child("userbalance").set(BalUp);
if (CoinFlip.load == 1) {
CoinOutcome();
}
else {
RouOutcome();
}
});
}
function RouOutcome(UserID) {
var OutCome = 0 + (Math.random() * 10000);
var UserID = firebase.auth().currentUser.uid;
if (OutCome <= 10000) {
if (Roulette.choice == 1) {
alert("You won");
var dbRoot = firebase.database().ref("Users").child(UserID);
dbRoot.once("value", snap => {
var cData = snap.val();
var cBet = cData.coinbet;
var uBal = cData.userbalance;
var WinBal = cBet * 2 + uBal
var NewBal = firebase.database().ref("Users").child(UserID).child("userbalance").set(WinBal);
//UpdateBal();
Roulette.comp = 1;
LoadTime();
});
}
else {
alert("you lost/didn't place bet");
Roulette.comp = 1;
LoadTime();
}
}
else if ((OutCome >= 4738) && (OutCome <=9474)) {
var UserID = firebase.auth().currentUser.uid;
if (Roulette.choice == 2) {
alert("You won");
var dbRoot = firebase.database().ref("Users").child(UserID);
dbRoot.once("value", snap => {
var cData = snap.val();
var cBet = cData.coinbet;
var uBal = cData.userbalance;
var WinBal = cBet*2+uBal
var NewBal = firebase.database().ref("Users").child(UserID).child("userbalance").set(WinBal);
//UpdateBal();
LoadTime();
});
}
else {
alert("you lost/didn't place bet");
LoadTime();
}
}
else {
var UserID = firebase.auth().currentUser.uid;
if (Roulette.choice == 3) {
alert("You won");
var dbRoot = firebase.database().ref("Users").child(UserID);
dbRoot.once("value", snap => {
var cData = snap.val();
var cBet = cData.coinbet;
var uBal = cData.userbalance;
var WinBal = cBet*14+uBal
var NewBal = firebase.database().ref("Users").child(UserID).child("userbalance").set(WinBal);
//UpdateBal();
LoadTime();
});
}
else {
alert("you lost/didn't place bet");
LoadTime();
}
}
}
Thanks very much for your help, if you need any more info please say.
Here is an example I created for you to follow. You don't show you attempt at resetting the bar so this is the best I can do at explaining for now.
var pBar = document.getElementById("progressBar");
var pText = document.getElementById("progressText");
startTimer();
function startTimer() {
var downIncrement = 10;
var DownTime = setInterval(function() {
var currentValue = pBar.getAttribute("aria-valuenow");
var newValue = currentValue - downIncrement;
pBar.setAttribute("aria-valuenow", newValue);
pBar.style = "width:" + newValue + "%";
pText.textContent = newValue / 10;
if (newValue <= 0) {
console.log("time is up!");
clearInterval(DownTime);
var Roulette = storewager();
if (Roulette.bet == 1) {
RouOutcome();
} else {
LoadTime();
}
}
},
1000);
}
function storewager() {
console.log("done with store wager");
return {
bet: 1
};
}
function RouOutcome() {
console.log("done with RouOutcome");
// restart progress bar
LoadTime();
}
function LoadTime() {
pBar.setAttribute("aria-valuenow", 100);
pBar.style = "width: 100%";
pText.textContent = "10";
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="progress">
<div id="progressBar" class="progress-bar" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width:100%">
<span id="progressText">10</span>
</div>
</div>
I ran into a deadly chaos on datepicker issues.
Who can solve my problem I can give 100 point as a return.
When I click the calendar on 2016-08-23 it will show me the 2016-08-22 as the date value.
Furthermore, the date value in angular model is also not correct.
I want to make the output can be consistent.
To reproduce the buggy issue, change your timezone between LA and TOKYO
DEMO site: https://test.jiyubi.com/tour_package/home
controller js
app.controller('tourPackageStartDatePickerCtrl',
function ($scope) {
$scope.initStartDate = function () {
$scope.startDate = $scope.startDate || null;
};
$scope.initStartDate();
$scope.dateOptions = {
baseDate: $scope.startDate,
minDate: $scope.startDate || moment.utc().toDate(),
};
$scope.openStartDateClick = function () {
$scope.startDatePopup.opened = true;
};
});
app.controller('tourPackageEndDatePickerCtrl',
function ($scope, $rootScope) {
$scope.clear = function () {
$scope.endDate = null;
};
$scope.endDateOptions = {
dateDisabled: disabledDays,
baseDate: new Date(),
};
$scope.openEndDateClick = function () {
$scope.endDatePopup.opened = true;
};
$scope.$watch("endDate", function (new_val, old_val) {
if (new_val && moment(new_val).isValid()) {
setTravelDateRange($scope.startDate, $scope.endDate);
}
}, true)
function setTravelDateRange(startDate, endDate) {
var start_date = moment_with_TAIPEI_TZ(startDate).format("YYYY/MM/DD");
var end_date = moment_with_TAIPEI_TZ(endDate).format("YYYY/MM/DD");
moment(startDate.toDateString()).tz("Asia/Taipei").format("YYYY/MM/DD");
$scope.q_param.startDate = start_date;
$scope.q_param.date_range = start_date + "-" + end_date;
}
});
helper.js
function moment_with_TAIPEI_TZ(time){
return moment(time).tz("Asia/Taipei");
}
function MOMENT_WITH_LOCAL(time){
return moment(time).local();
}
function discard_timezone(value) {
return moment.utc(value).format(DEFAULT_MOMENT_TIME_FORMAT);
}
function getYYYYMMDD(value) {
return moment.utc(value).format("YYYY/MM/DD");
}
function date_without_timezone(value) {
return moment.utc(value).toDate();
}
It's may be because of a timezone issue.
Could you please try to convert to date without considering the timezone?
this.convertToDateWithoutTimezone = function(date) {
if (date.toString().match(/(\d\d\d\d)-(\d\d)-(\d\d)/)) {
var year = $filter('date')(date.slice(0, 10), 'yyyy'),
month = $filter('date')(date.slice(0, 10), 'MM'),
day = $filter('date')(date.slice(0, 10), 'dd');
return new Date(year, month - 1, day);
} else {
return new Date(date);
}
};
I'm using this Calendar, and "i'm forced to use it" and i'm wondering if you could help me sorting out a small issue i'm having.
Calendar: http://www.bulgaria-web-developers.com/projects/javascript/calendar/
I have 2 input fields that this calendar is on,
<input type="text" id="cr_date_from" />
<input type="text" id="cr_date_to" />
And after selecting the date in "date_from" i need it to jump to "date_to" and have the same date as selected in the date_from field. As this will not cause confusion when people are selecting a date months ahead in time, and not to scroll all the way to that date in the date_to as well...
I've tried researching on this for a while now without luck, so i'm hoping you guys are able to help me out..
Appreciate all help on this!
Here is also the javascript for those interested...
bindSearch: function () {
var self = this,
dateFrom = new Calendar({
element: "cr_date_from",
//dateFormat: "Y-m-d",
dateFormat: self.opts.dateFormat,
monthNamesFull: self.opts.monthNamesFull,
dayNames: self.opts.dayNames,
disablePast: true,
months: 3,
onSelect: function () {
reCalc.call(self);
}
}),
dateTo = new Calendar({
element: "cr_date_to",
//dateFormat: "Y-m-d",
dateFormat: self.opts.dateFormat,
monthNamesFull: self.opts.monthNamesFull,
dayNames: self.opts.dayNames,
disablePast: true,
months: 3,
onSelect: function () {
reCalc.call(self);
}
}),
lnkFrom = document.getElementById("crDateFrom"),
lnkTo = document.getElementById("crDateTo"),
btnQuote = document.getElementById("crBtnQuote"),
btnMap = document.getElementById("crBtnMap"),
sameLoc = document.getElementById("cr_same_location"),
returnLoc = document.getElementById("crReturnBox");
self.elFrom = document.getElementById("cr_date_from");
self.elTo = document.getElementById("cr_date_to");
self.elHFrom = document.getElementById("cr_hour_from");
self.elMFrom = document.getElementById("cr_minutes_from");
self.elHTo = document.getElementById("cr_hour_to");
self.elMTo = document.getElementById("cr_minutes_to");
function reCalc() {
var from = Date.parseExact(this.elFrom.value, dateFormat(self.opts.dateFormat, 'datejs')).getTime() + (parseInt(this.elHFrom.value, 10) * 3600000) + (parseInt(this.elMFrom.value, 10) * 60000),
to = Date.parseExact(this.elTo.value, dateFormat(self.opts.dateFormat, 'datejs')).getTime() + (parseInt(this.elHTo.value, 10) * 3600000) + (parseInt(this.elMTo.value, 10) * 60000),
nd = document.getElementById("crNumDays"),
days;
if (from !== null && to !== null) {
days = Math.ceil((to - from) / 86400000);
if (days > 0) {
nd.lastChild.innerHTML = days;
nd.style.display = "";
} else {
nd.style.display = "none";
}
} else {
nd.style.display = "none";
}
}
if (lnkFrom) {
lnkFrom.onclick = function (e) {
if (e && e.preventDefault) {
e.preventDefault();
}
dateFrom.isOpen ? dateFrom.close() : dateFrom.open();
return false;
};
}
if (lnkTo) {
lnkTo.onclick = function (e) {
if (e && e.preventDefault) {
e.preventDefault();
}
dateTo.isOpen ? dateTo.close() : dateTo.open();
return false;
};
}
if (btnMap) {
btnMap.onclick = function (e) {
self.overlayMap.open();
if (e && e.preventDefault) {
e.preventDefault();
}
return false;
}
}
if (sameLoc && returnLoc) {
function bindLoc(el) {
if (this.checked) {
el.style.display = "none";
} else {
el.style.display = "";
}
}
sameLoc.onchange = function () {
bindLoc.call(this, returnLoc);
};
sameLoc.onclick = function () {
bindLoc.call(this, returnLoc);
};
}
if (btnQuote) {
btnQuote.onclick = function () {
this.disabled = true;
if (!self.validateSearch(this)) {
this.disabled = false;
return;
}
self.passed.first = true;
self.loadCars.apply(self, [JABB.Utils.serialize(document.getElementById("crFormSearch"))]);
};
}
},
I can go back from date to year in datepicker. But when I try to come back to date, when i clicked on year, datepicker automatically hide.
var datePickerOptions = this.data || {};
datePickerOptions.format = datePickerOptions.format || "mm-dd-yyyy";
datePickerOptions.language = datePickerOptions.language || this.lang.code;
var $context = this;
var dateContainer = this.container.find(".datepicker");
dateContainer.datepicker(datePickerOptions).on('changeDate', function (ev) {
// here i'm getting the value
});
This because of bootstrap-datepicker.js .
on click event you can find like following.
case 'span':
if (!target.is('.disabled')) {
this.viewDate.setUTCDate(1);
if (target.is('.month')) {
var day = 1;
var month = target.parent().find('span').index(target);
var year = this.viewDate.getUTCFullYear();
this.viewDate.setUTCMonth(month);
this._trigger('changeMonth', this.viewDate);
if (this.o.minViewMode === 1) {
this._setDate(UTCDate(year, month, day,0,0,0,0));
}
} else {
var year = parseInt(target.text(), 10)||0;
var day = 1;
var month = 0;
this.viewDate.setUTCFullYear(year);
this._trigger('changeYear', this.viewDate);
if (this.o.minViewMode === 2) {
this._setDate(UTCDate(year, month, day,0,0,0,0));
}
}
this.showMode(-1);
this.fill();
}
instead of this.fill(), if you use like following code, this will work as you expected.
if (target.is('.month')) {
if (!this._o.changeMonth) {
this.fill();
}
}
else {
if (!this._o.changeYear) {
this.fill();
}
}
I hope, this will help you. :-)