Displaying count down timer in Sencha Touch 2 - sencha-touch-2

I need to display a countdown timer, implemented it using delayed task.
code as below:
var task = Ext.create('Ext.util.DelayedTask', function() {
if (sec < 1 && min > 0) {
min--;
sec = 60;
}
if (min == 0 && sec == 1) {
task.cancel();
}
sec--;
Ext.getCmp('minute').setHtml(min);
Ext.getCmp('second').setHtml(sec);
console.log('minute is' + min + 'second is' + sec);
task.delay(1000);
}, this);
task.delay(1000);
With the above implementation, function gets called only once.
Looking at the discussion at this thread
Auto Refresh the List in Sencha Touch Application the above code should work. But, it is not working. What could be wrong in my code? Thanks.

As far as I know, Ext.util.DelayedTask is meant for delaying a task without executing it.
This can be useful for delaying an Ajax-call on a form, as you can see in the docs:
This method is especially useful for things like detecting whether a user has finished typing in a text field. [..] You can use this class to buffer the keypress events for a certain number of milliseconds, and perform only if they stop for that amount of time.
Why don't you just use a regular setTimeout? Something like http://jsfiddle.net/EreaP/ works perfectly.

Late response:
Ext.define('MyApp.view.TimerClock', {
extend: 'Ext.Container',
xtype: 'timerClock',
duration: 3 * 60 * 60, //default to 3 hour
paused: false,
clockIntervalHook: undefined,
config: {
listeners: {
initialize: function () {
this.start();
}
}
},
start: function () {
var me = this,
duration = me.duration,
updateClock = function () {
if (me.isPaused()) {
return;
}
me.setHtml(me.formatTime(duration--));
if (duration <= 0) {
me.stop();
}
};
me.clockIntervalHook = setInterval(updateClock, 1000);
return me;
},
pause: function () {
this.paused = true;
return this;
},
isPaused: function () {
return this.paused == true
},
resume: function () {
this.paused = false;
},
restart: function () {
this.stop();
this.start();
},
stop: function () {
clearInterval(this.clockIntervalHook);
return this;
},
//format the given seconds into "HH:MM:SS" format
//override this if you need custom behavior
formatTime: function (seconds) {
var hours = Math.floor(seconds / 3600);
hours = hours <= 9 ? "0" + hours : hours;
seconds %= 3600;
var minutes = Math.floor(seconds / 60);
minutes = minutes <= 9 ? "0" + minutes : minutes;
seconds %= 60;
seconds = seconds <= 9 ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds
}
});
Any other view, add the timer simply using
{ xtype : 'timerClock' }

Related

Video Element - Skip Multiple Sections [duplicate]

I have a requirement where I need to play a html video with time jumps.
Scenario is like this:-
I have an array that contains time markers like this const obj = [{start: 2.64, end: 5.79}, {start: 7.95, end: 8.69}].
The requirement is that the video should start from 2.64 and play till 5.79 and then jump to 7.95 and then end at 8.69 and so on.
My solution is like this:-
const timers = this.state.timers;
let video = this.videoRef;
if (video) {
let index = 0;
video.addEventListener("timeupdate", () => {
if (parseInt(video.currentTime) == parseInt(timers[timers.length - 1].end)) {
video.pause()
}
if (timers[index]) {
if (parseInt(video.currentTime) == parseInt(timers[index].end)) {
if (index <= timers.length - 1) {
index++;
if (timers[index]) {
video.currentTime = timers[index].start;
}
}
}
}
this.setState({
tickTime: Math.ceil(video.currentTime)
})
})
video.play().then(res => {
video.currentTime = timers[0].start
})
}
It is working fine but when the video currenttime is like 2.125455 and in time object has end time 2.95, the parseInt function make both the time 3 and the video jumps to 3, so the 8 ms never plays, these 8ms are also very critical in my case
any solution on this please?
I am stuck for a while now
Well, I was able to resolve the problem
Thanks anyways
Here is the solution if anyone else facing it
const timers = this.state.timers;
let video = this.videoRef;
if (video) {
let index = 0;
video.addEventListener("timeupdate", () => {
if (video.currentTime >= timers[timers.length - 1].end) {
video.pause()
}
if (timers[index]) {
if ((video.currentTime) >= (timers[index].end)) {
if (index <= timers.length - 1) {
index++;
if (timers[index] && video.currentTime < timers[index].start) {
video.currentTime = timers[index].start;
}
}
}
}
this.setState({
tickTime: Math.ceil(video.currentTime)
})
})
video.play().then(res => {
video.currentTime = timers[0].start
})
}

Axios update value outside of then to break the loop

I'm still currently learning on using React Native.
What I'm trying to do is update the limit value to 1 so it would break the while loop, but I am not sure on how to execute it since I can't update the value from inside the .then() in Axios POST call.
Glad if anyone would point out any method to handle this. Thank you for your help.
var limit = 0;
while (limit == 0) {
running = running + 20;
console.log("restart");
postDataCalories = {
"query": `${running} minutes run and ${walking} minutes walking`,
"gender":"male",
// "nf_calories": 363.62,
"weight_kg":63.5,
"height_cm":167.64,
"age":30
};
console.log(`${running} minutes run and ${walking} minutes walking`);
axios.post('https://trackapi.nutritionix.com/v2/natural/exercise', postDataCalories, axiosConfig2)
.then((res3) => {
console.log("exercise RESPONSE RECEIVED: ", res3);
let caloriesFood = res2.data.foods[0].nf_calories;
let caloriesExercise = res3.data.exercises[0].nf_calories;
let caloriesDifferences = caloriesFood - caloriesExercise;
console.log("hi " + caloriesDifferences);
if (caloriesDifferences < 50){
console.log('done');
limit = 1;
} else {
console.log('nope');
}
})
}
That's right in your case you cannot break the while loop inside the then-function because that function is called at a different moment in time (they call it asynchronous).
There are two things you can do. If you have access to await/async in your environment you could rewrite it to:
async someFunction() {
var limit = 0;
var running = 1; // arbitrarily start at 1.
while (limit == 0) {
running = running + 20;
console.log("restart running " + running);
postDataCalories = {
"query": `${running} minutes run and ${walking} minutes walking`,
"gender":"male",
// "nf_calories": 363.62,
"weight_kg":63.5,
"height_cm":167.64,
"age":30
};
console.log(`${running} minutes run and ${walking} minutes walking`);
var res3 = await axios.post('https://trackapi.nutritionix.com/v2/natural/exercise', postDataCalories, axiosConfig2)
console.log("exercise RESPONSE RECEIVED: ", res3);
let caloriesFood = res2.data.foods[0].nf_calories;
let caloriesExercise = res3.data.exercises[0].nf_calories;
let caloriesDifferences = caloriesFood - caloriesExercise;
console.log("hi " + caloriesDifferences);
if (caloriesDifferences < 50){
console.log('done');
limit = 1;
// you may also do:
break;
} else {
console.log('nope');
}
}
}
}
For usual web conditions it requires either a modern browser (Firefox/Chrome) (or when you have babel / regenerator-runtime might do the trick, maybe your setup is already capable of transpiling this/running this.)
If you dont have access to async/await then you need to apply recursion (to work around the synchronicity). Normally you can perform the tasks sequentially (in a row, step by step, using a while loop), now you would write something like:
function runTheLoop(running, walking) {
postDataCalories = {
"query": `${running} minutes run and ${walking} minutes walking`,
"gender":"male",
// "nf_calories": 363.62,
"weight_kg":63.5,
"height_cm":167.64,
"age":30
};
console.log(`${running} minutes run and ${walking} minutes walking`);
axios.post('https://trackapi.nutritionix.com/v2/natural/exercise', postDataCalories, axiosConfig2)
.then((res3) => {
console.log("exercise RESPONSE RECEIVED: ", res3);
let caloriesFood = res2.data.foods[0].nf_calories;
let caloriesExercise = res3.data.exercises[0].nf_calories;
let caloriesDifferences = caloriesFood - caloriesExercise;
console.log("hi " + caloriesDifferences);
if (caloriesDifferences < 50){
console.log('done');
// limit = 1;
return;
} else {
console.log('nope');
// This is the recursive variant of "running the loop again"
return runTheLoop(running + 20, walking + 20);
}
})
}
}
// Somewhere:
console.log("restart");
// one minute of walking and one minute of running.
runTheLoop(1, 1);
Note: I've used your your code to make the examples relevant in to your situation, I could not test it out myself so it may not work directly if you copy and paste this.

I am wondering how to make a clock timer in react native that starts from 00:00:00

I want to make a clock timer that starts on page load. like below
00 m: 06 s
start a setInterval in the componentDidMount and update the state every second.
state = {
time: 0,
};
componentDidMount() {
this.timer = setInterval(() => {
this.setState(prev => {
return {
time: prev.time + 1,
};
});
}, 1000);
}
componentWillUnmount() {
clearInterval(this.timer);
}
and extract seconds,minutes,hours
const { time } = this.state;
const hours = Math.floor(time / 3600);
const minutes = Math.floor((time - hours * 3600) / 60);
const seconds = time - minutes * 60 - hours * 3600;
Here is an expo demo

setInterval doesn't fire in vue

im learning vue and setInterval doesn't work like in normal javascript? the problem is that my update function doesn't get fired.
start gets fired from a button, and hours/minutes/seconds are bound to input fields with v-model, i get all console.logs before the setInterval.
export default Vue.extend({
name: "timer-c",
data() {
return {
startDate: undefined,
hours: "",
minutes: "",
seconds: "",
timeLeft: undefined,
endDate: undefined,
interval: undefined,
text: "00:00:00",
sub: undefined,
};
},
methods: {
start: function() {
if (this.sub === undefined) {
let sum = 0;
if (this.seconds.match(/^\d+$/)) {
sum = sum + this.seconds * 1000;
console.log(sum);
}
if (this.minutes.match(/^\d+$/)) {
sum = sum + this.minutes * 60 * 1000;
}
if (this.hours.match(/^\d+$/)) {
sum = sum + this.hours * 60 * 60 * 1000;
}
if (sum === 0) {
console.log(this.$refs.br_start);
this.failed = true;
} else {
console.log(sum);
this.failed = false;
this.endDate = new Date(Date.now() + sum);
console.log(this.endDate);
this.startDate = new Date(Date.now());
console.log(this.startDate);
this.interval = setInterval(time => this.update, 1000);
//this.sub = this.interval.subscribe(time => this.update(time));
}
}
},
update: function() {
console.log('test');
const timeRemaining = Math.round((Date.now() - this.endDate) / 1000);
this.text = timeRemaining;
if (new Date(Date.now()) >= this.endDate) {
console.log("test");
}
},
Try to not return the function but execute it
this.interval = setInterval(time => { this.update(time) }, 1000);

Changing the date in Countdown

How can I change the date from my countdown?
I know it is working but can't find the place to change the date!
I'm a newby, sorry for asking!
(function($) {
$.fn.countdown = function(options, callback) {
//custom 'this' selector
thisEl = $(this);
//array of custom settings
var settings = {
'date': null,
'format': null
};
//append the settings array to options
if(options) {
$.extend(settings, options);
}
//main countdown function
function countdown_proc() {
eventDate = Date.parse(settings['date']) / 1000;
currentDate = Math.floor($.now() / 1000);
if(eventDate <= currentDate) {
callback.call(this);
clearInterval(interval);
}
seconds = eventDate - currentDate;
days = Math.floor(seconds / (60 * 60 * 24)); //calculate the number of days
seconds -= days * 60 * 60 * 24; //update the seconds variable with no. of days removed
hours = Math.floor(seconds / (60 * 60));
seconds -= hours * 60 * 60; //update the seconds variable with no. of hours removed
minutes = Math.floor(seconds / 60);
seconds -= minutes * 60; //update the seconds variable with no. of minutes removed
//conditional Ss
if (days == 1) { thisEl.find(".timeRefDays").text("day"); } else { thisEl.find(".timeRefDays").text("days"); }
if (hours == 1) { thisEl.find(".timeRefHours").text("hour"); } else { thisEl.find(".timeRefHours").text("hours"); }
if (minutes == 1) { thisEl.find(".timeRefMinutes").text("minute"); } else { thisEl.find(".timeRefMinutes").text("minutes"); }
if (seconds == 1) { thisEl.find(".timeRefSeconds").text("second"); } else { thisEl.find(".timeRefSeconds").text("seconds"); }
//logic for the two_digits ON setting
if(settings['format'] == "on") {
days = (String(days).length >= 2) ? days : "0" + days;
hours = (String(hours).length >= 2) ? hours : "0" + hours;
minutes = (String(minutes).length >= 2) ? minutes : "0" + minutes;
seconds = (String(seconds).length >= 2) ? seconds : "0" + seconds;
}
//update the countdown's html values.
if(!isNaN(eventDate)) {
thisEl.find(".days").text(days);
thisEl.find(".hours").text(hours);
thisEl.find(".minutes").text(minutes);
thisEl.find(".seconds").text(seconds);
} else {
alert("Invalid date. Here's an example: 12 Tuesday 2012 17:30:00");
clearInterval(interval);
}
}
//run the function
countdown_proc();
//loop the function
interval = setInterval(countdown_proc, 1000);
}
}) (jQuery);
Look for a separate code, or add these lines. Change function/variable/date accordingly
/** Countdown Timer **/
$(document).ready(function() {
"use strict";
$("#countdown").countdown({
date: "20 sep 2020 12:00:00", /** Enter new date here **/
format: "on"
},
function() {
// callback function
});
});
What you provided looks to be the function (the engine) and the code you're looking for calls this. I think you'll find what you are looking for is a line that says something like:
$.fn.countdown({
'date': 'PLACE DATE HERE',
'format': null
}, function(){
//Some code here
);
The values may be slightly different but it'll be something like that. When you call that function, you provide the date to work off of.