Question
The DigitalWatch sample project contains a date update function that behaves differently when the application starts on Sunday (day 0) compared to other days. Here's the problematic code:
function updateDate(prevDay) {
var datetime = tizen.time.getCurrentDateTime(),
nextInterval,
strDay = document.getElementById("str-day"),
strFullDate,
getDay = datetime.getDay(),
getDate = datetime.getDate(),
getMonth = datetime.getMonth();
if (prevDay !== null) {
if (prevDay === getDay) {
nextInterval = 1000;
} else {
nextInterval = (23 - datetime.getHours()) * 60 * 60 * 1000 +
(59 - datetime.getMinutes()) * 60 * 1000 +
(59 - datetime.getSeconds()) * 1000 +
(1000 - datetime.getMilliseconds()) + 1;
}
}
if (getDate < 10) {
getDate = "0" + getDate;
}
strFullDate = arrDay[getDay] + " " + getDate + " " + arrMonth[getMonth];
strDay.innerHTML = strFullDate;
if (timerUpdateDate) {
clearTimeout(timerUpdateDate);
}
timerUpdateDate = setTimeout(function() {
updateDate(getDay);
}, nextInterval);
}
The issue occurs because:
- When the method is first called with parameter 0 (Sunday), it sets a 1-second interval for updates
- On other days (1-6), it correctly calculates the time until midnight
- This causes the function to be called every second all day when started on Sunday
A temporary fix was found by changing the initial parameter to -1, but this doesn't seem like the intended behavior.
Answer
Problem Understanding
The issue stems from how JavaScript handles the prevDay parameter in the date update logic. When:
prevDayis 0 (Sunday) andgetDay()returns 0, the function sets a 1-second interval- This differs from the intended behavior where it should calculate the time until midnight
Solution Methods
-
Parameter Check Modification:
- Change the initial parameter from 0 to null or undefined
- Modify the condition to handle falsy values properly
-
Code Restructuring:
- Move the date update logic into the main time update function
- Avoid separate setTimeout calls for date updates
Code Examples
Here's an improved version:
function updateDateTime() {
var datetime = tizen.time.getCurrentDateTime();
var currentDay = datetime.getDay();
// Update time display
// ... existing time update code ...
// Update date display if day changed
if (typeof lastDay === 'undefined' || lastDay !== currentDay) {
var getDate = datetime.getDate();
if (getDate < 10) getDate = "0" + getDate;
var strFullDate = arrDay[currentDay] + " " + getDate + " " + arrMonth[datetime.getMonth()];
document.getElementById("str-day").innerHTML = strFullDate;
lastDay = currentDay;
}
// Schedule next update
timerUpdate = setTimeout(updateDateTime, 1000);
}
Additional Tips
- Consider using
Dateobject methods directly instead of Tizen's time API for simpler date handling - For production code, implement proper error handling around time API calls
- Test thoroughly across different time zones and daylight saving transitions