I'm working on a calendar based dashboard widget that I want to automatically updated at the start of a new day. However, I can't seem to get it to actually update. It seems to work fine running in a browser. I've also tried manually entering the setTimeout delay to something much shorter (like 1 or 2 minutes) and that seems to work.
This is the code I have:
function Calendar() {
var _self = this;
this.daytimer = null;
this.daytimerAction = function() {
_self.updateCurrentDate();
}
this.resetDaytimer();
}
Calendar.prototype.resetDaytimer = function() {
var today = new Date(),
tomorrow = new Date();
if (this.daytimer) {
clearTimeout(this.daytimer);
this.daytimer = null;
}
tomorrow.setDate(today.getDate() + 1);
tomorrow.setHours(0);
tomorrow.setMinutes(0);
tomorrow.setSeconds(1);
this.daytimer = setTimeout(this.daytimerAction, tomorrow.getTime() - today.getTime());
};
Calendar.prototype.updateCurrentDate = function() {
// Run code to update the day display
this.resetDaytimer();
};
Any thoughts? The only thing I can think of is that dashboard is pausing/cancelling the setTimeout when dashboard isn't running. Maybe there is a way to reset the timeout when dashboard is reactivated?
Figured it out. Apple documentation outlines the widget.onshow event that I can use to restart the timer as well as call updateCurrentDate() directly. There is also a widget.onhide event that can be used to pause the timer.
Related
I'm using videojs to play videos on the site and I'm trying to create log on video streams but I have difficulty logging users seeking in videos. I need seek start and end time and it seems that the built in handleSeeked() function in videojs does the job but I can't get it to work. Does anybody know how to use this function?
Update
It seems that this question is about the same problem but the solutions aren't fully working and each one has a little problem.
I was able to get what I wanted with the following code but I had to handle everything on my own so if there's still a better way to do this I'd be happy if you could help me.
var previousTime = 0,
currentTime = 0,
completeTime = 0,
position = 0;
player.on('timeupdate', function () {
previousTime = currentTime;
currentTime = Math.floor(player.currentTime());
// save 'position' so long as time is moving forward with each update
if (previousTime < currentTime) {
position = previousTime;
console.log('pos',position)
previousTime = currentTime;
console.log('pre',previousTime)
}
});
player.on('seeked', function () {
completeTime = Math.floor(player.currentTime());
console.log("User came from: " + position);
console.log("User ended at: " + completeTime);
position= Math.floor(player.currentTime())
});
I am trying to get the time difference between the switching of browser tab.By this what I meant to say is we are now on ember web app and I switch to some other tab.Now when I return to ember web app I want to get the time difference of these two event.I am not sure how to attain this.Any lead will help.
Do in controller or compoenent :
diff: Ember.computed('endTime',function(){
let start = this.get('startTime');
let end = this.get('endTime');
var timeDiff = Math.abs(end - start);
var diffSec = Math.ceil(timeDiff / (1000));
return diffSec;
}),
init(){
this._super(...arguments);
const self = this;
Ember.$(window).blur(function(e) {
self.set('endTime', new Date());
});
Ember.$(window).focus(function(e) {
self.set('startTime', new Date());
});
}
and in corresponding template :
Difference in second : {{diff}}
Please take a look at this twiddle
I have an existing Telerik AppBuilder application that previously had working notifications before a major overhaul was done on the app. The app uses Cordova 3.7.0 and is attempting to implement the localnotifications plugin, whose source code can be found here : https://github.com/katzer/cordova-plugin-local-notifications . I installed it using the instructions specified in Telerik's "Verified Plugins" Documentation. However, it no longer functions. Through various alerts, alert(windows.plugins) and alert(cordova.plugins) is always undefined, as is alert(windows.plugins.notifications) and all permutations thereof. I saw responses to other replies saying that window.plugins would always be undefined and deprecated, but window.plugins.[PLUGIN_NAME] would exist. However, this does not seem to be the case, and this instead breaks the javascript. Below is the code current being used
define(['jQuery', 'base64'], function ($, base64) {
....
var that = this;
that.alert("starting");
document.addEventListener("deviceready", function() {
that.alert(JSON.stringify(window.plugins));
}, false);
....
}
The previously functioning code was
if (that.hasNotificationPlugin()) {
that.clearNotifications(function() {
console.info('Setting notifications');
// Schedule notifications for each day from the schedule
$.each(data.DeliveryDaysThisWeek, function (i, day) {
var dow = day.DayOfWeek;
// Schedule notifications for each store within a day
$.each(day.Stores, function (i, store) {
// Only schedule the notification if the user
// hasn't disabled notifications for this store
if (that.get('notification' + store.StoreId) !== 'false') {
var cutoffDate = new Date(store.CutOffDateTime);
var cutoffString = $.format.date(cutoffDate, 'h:mm a');
// Schedule it 30 minutes before the cutoff time
// or using the user defined time
var time = parseInt(that.get('notificationTime'));
if (isNaN(time)) {
that.set('notificationTime', "30");
time = 30;
}
var notifDate = new Date(cutoffDate.getTime() - time * 60 * 1000);
// Only schedule it if it's in the future
if (notifDate > new Date()) {
window.plugin.notification.local.add({
id: (dow * 100000 + store.DeliveryTimes[0].DeliveryTimeId).toString(),
date: notifDate,
message: "The cutoff time is almost up! Place your order by " + cutoffString,
title: store.Store.Restaurant.RestaurantName.trim(),
json: JSON.stringify({StoreId: store.StoreId}),
icon: 'icon'
});
that.alert(message) is a shortcut function for navigator.notificaiton.alert(message, false, "COMPANY_NAME") and works fine.
Why
this plugin uses cordova.plugins... or window.plugin..., can you try that? see the line of code responsible for this
Someone made me aware of some flaws in an application I'm working on (mostly within my JavaScript on the front-end), that leaves open the possibility of, say, clicking a ton of buttons at once and sending out a ton of transactional emails. This is clearly not good.
I think one way to handle this in ExpressJS is by using app.all() to count the number of requests that happen within a certain timeframe. I'd store this in the session metadata with timestamps, and if more than X requests happen in Y time, I cut them off for awhile until the limit expires.
Has anyone done this before or have any tips/hints to help me out? Something that's easy to drop in and out of my app is preferable. Thanks!
You could use the Collate object in your webpage.
function Collate(timeout) {
this.timeout = timeout || 1000;
}
Collate.prototype = {
time: 0,
idle: function() {
var t = new Date().getTime();
return (t - this.time > this.timeout && (this.time = t));
},
prefer: function(func) {
this.func = func;
clearTimeout(this.timer);
this.timer = setTimeout(func, this.timeout);
}
};
If you want a function to run once and not run again within the next 1 second.
Like if you want to prevent the user from submitting a form many times, you do this:
var timer = new Collate(3000); //3 seconds
button1.onclick = function() {
if(timer.idle()) {
button1.form.submit();
} else alert("Don't click too quickly!");
}
//or on the form tag
<script>var submitTimer = new Collate(3000);</script>
<form action="post" onsubmit="return submitTimer.idle();">
If you expect an event to fire multiple times and only want to react to the last time it fires.
Like if you want to search after a user has finished typing, you do this:
var timer = new Collate(700); //0.7 seconds
textfield1.onkeyup = function() {
timer.prefer(function() {
autocomplete.search(textfield1.value);
});
};
I've built a simple JavaScript-based timer for a mobile webapp; for the sake of example:
var a = 0;
setInterval(function() {
console.log('a', a);
a++;
}, 1000);
This runs just fine in both Mobile Safari and Android Browser. It will log to console every second and increment the value of a accordingly. (Okay, Android Browser doesn't have console.log support, but let's assume it does.)
The issue: if the screen times out (i.e. user stopped interacting with the page), the setInterval function pauses. It resumes when the user turns on their screen again. This won't work for me as I need timer to keep running.
The questions: Is there a way to prevent the setInterval function from pausing when the screen times out? If not, is it possible to prevent the screen from timing out? Any other alternatives?
Thanks in advance!
Basically, no. The phone enters a sleep state to save battery when the screen times out. Since you can't see anything anyway, a large number of processing tasks are stopped. Similar things will occur when you change tabs/windows (the page is unloaded from memory). Right now there is no way to request that the device stays on from a web application. Future support in Android for accessing hardware may provide this functionality, but personally I doubt it.
If you need always running support, you'll need to write native applications for both systems (plus on Android it can always run).
You can use the Page Visibility API to detect when the page is hidden or visible. For example, if the user navigates away from the browser and back again or the screen turns off and on.
I used this answer to help create by solution.
You will need to store the time you set your interval. Then when the visibilityChange event listener indicates the document is visible again, you can calculate the amount of time that has passed since you first started the interval and update your data as needed.
In my case I was creating a count down timer in my Angular2 project. My page was running on an iPad and the timer was pausing whenever the screen turned off. So I added the event listener in my ngOnInit(). Then when the screen turned back on I could update my timer to show the correct time left since it was started.
I am using the moment npm package to handle my date time.
The timerInfo object is a class variable that gets updated by the interval callback. self.zone.run() is used to propagate the changes to the DOM so that the updated time gets displayed.
Written in typescript:
private timerInfo:{
days?:number,
hours?:number,
minutes:number,
seconds:number
};
private startTime:Moment = moment();
private timerDuration:number = 20; // in minutes
private timerHandle:any;
ngOnInit() {
this.setVisibilityListener();
}
private setVisibilityListener():void {
var self = this;
var hidden, visibilityState, visibilityChange;
if (typeof document.hidden !== "undefined") {
hidden = "hidden";
visibilityChange = "visibilitychange";
visibilityState = "visibilityState";
}
var document_hidden = document[hidden];
document.addEventListener(visibilityChange, function () {
if (document_hidden != document[hidden]) {
if (document[hidden]) {
// Document hidden
console.log("document hidden");
} else {
// Document shown
console.log("document shown; setCountDownTimer()");
self.setCountDownTimer();
}
document_hidden = document[hidden];
}
});
}
private setCountDownTimer():void {
var self = this;
if (self.startTime) {
var startMoment = moment(self.startTime);
var endMoment = startMoment.add(self.timerDuration, "minutes");
console.log("endMoment: ", endMoment.toISOString());
self.clearTimer();
var eventTime = endMoment.unix();
var currentTime = moment().unix();
var diffTime = eventTime - currentTime;
var duration = moment.duration(diffTime * 1000, 'milliseconds');
var interval = 1000;
// if time to countdown
if (diffTime > 0) {
self.timerHandle = setInterval(() => {
self.zone.run(() => {
var diff = duration.asMilliseconds() - interval;
if (diff < 0) {
self.clearTimer();
self.timerComplete();
} else {
duration = moment.duration(duration.asMilliseconds() - interval, 'milliseconds');
self.timerInfo = {
days: moment.duration(duration).days(),
hours: moment.duration(duration).hours(),
minutes: moment.duration(duration).minutes(),
seconds: moment.duration(duration).seconds()
};
// console.log("timerInfo: ", JSON.stringify(self.timerInfo));
}
});
}, 1000);
} else {
self.timerComplete();
}
}
}
private clearTimer():void {
if (this.timerHandle) {
clearInterval(this.timerHandle);
this.timerHandle = null;
}
}