React native interval, Can't make it right way - react-native

Hi I'm just trying up setstate a component with interval.I put interval code in componentdidmount and clear it in componentWillUnmount.
It should stops intervalling when user navigates another screen but console logs says it continues.
Also i want to works this in every 1 second but when i put interval time as 1000 it works in 3 second
constructor(props) {
super(props);
this.state = {
text:'',
};
this._interval = null;
}
componentDidMount() {
if (!this._interval) {
console.log('this._interval',this._interval)
var endNew = new Date(this.props.end);
var distance = endNew.getTime() - newNow.getTime();
var hour = Math.floor(distance / 1000 / 60 / 60);
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
if (hour < 1 && minutes < 1 && seconds < 2) {
this.setState({isClosed: false});
} else {
this.setState({
textt: hour + ' h ' + minutes + ' m ' + seconds + 's',
});
}
}, 1000);
}
}
componentWillUnmount() {
clearInterval(this._interval);
clearTimeout(this._interval);
}
if (!this._interval) {
console.log('this._interval',this._interval)
and console log = this._interval null

In case you are using react-navigation stacknavigator won‘t callcomponentdidmount when pushing a new view on top.
As you can see in docs, you should rather subscribe to focus/blur.

Related

How could I change the value of this.buttonState in this scenary?

I'm having issues in this process . First is that I have a button in disabled state(true) and I need to change that value to false when the video is uploaded . I have this scenary and I think I got a windows object inside the changing method . Any idea, help please . I'm getting undefined value for the variable.
data: () => ({
buttonState: true} }),
changeBehavior() {
let self
(function () {
const input = document.getElementById('uploader')
self = this
console.log(this)
const changing = ({ target: { files } }) => {
if (input.files.length > 0) {
// self.buttonState = false
const video = document.getElementById('output-video')
video.src = URL.createObjectURL(files[0])
}
}
input.addEventListener('change', changing)
})()
const au = document.getElementById('output-video')
au.onloadedmetadata = () => {
const hidden = document.getElementById('hiddenSlider')
hidden.removeAttribute('hidden')
const muteHidden = document.getElementById('muteHidden')
muteHidden.removeAttribute('hidden')
self = this
self.range = [0, au.duration]
this.max = au.duration
const secNum = parseInt(au.duration, 10)
let hours = Math.floor(secNum / 3600)
let minutes = Math.floor((secNum - (hours * 3600)) / 60)
let seconds = secNum - (hours * 3600) - (minutes * 60)
if (hours < 10) {
hours = '0' + hours
}
if (minutes < 10) {
minutes = '0' + minutes
}
if (seconds < 10) {
seconds = '0' + seconds
}
document.getElementById('renderizado').innerHTML =
hours + ':' + minutes + ':' + seconds
}
},
<v-btn
id="run"
class="accent-3 blue ml-15"
dark
#click="$refs.inputUpload.click()"
>
<input
v-show="false"
id="uploader"
ref="inputUpload"
accept=".mkv,video/*"
type="file"
#click="changeBehavior"
>
Select to Upload Video
</v-btn>
<v-btn
id="doTrimming"
block
class="accent-3 blue mt-5"
dark
:disabled="buttonState"
#click="cutIt"
>
Trim Video Now
</v-btn>
Where you define self you need to assign this to it then.
changeBehavior() {
const self = this;
const callback = function() {
// now you can access the vue instance when in another functions scope
self.buttonState = true;
}
}

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

Vue: Can't dynamically insert value from function

I have data, timestamp, that comes from the server as a unix timestamp. I am trying to dynamically insert this in every second. I can get it to successfully console.log the time (console.log(x)) but it won't return it and insert the time in the DOM.
<template>
<div>
<span> {{ checkItemExpiry(timestamp) }}</span>
</div>
</template>
<script>
export default {
methods: {
convertTime: function(time) {
var sec_num = parseInt(time, 10);
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
let x = (hours + ":" + minutes + ":" + seconds);
console.log(x)
return x
},
checkItemExpiry: function(expireTimestamp) {
let startTime = expireTimestamp;
setInterval(() => {
let currentTime = (new Date()).getTime() / 1000;
this.convertTime((startTime-currentTime))
}, 1000);
}
}
}
</script>

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.

Displaying count down timer in 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' }