I am creating a simple countdown timer for a game. I am using CoffeeScript and Meteor. I have a Handlebars "Timer" template with a {{time}} expression.
Here is the code:
clock = 10
timeLeft = () ->
if clock > 0
clock--
else
"That's All Folks"
Meteor.clearInterval(interval)
interval = Meteor.setInterval(timeLeft, 1000)
if Meteor.isClient
Template.timer.time = interval
The above code just gives me a static display of 8 or 6 instead of the countdown timer.
If I add a few console.log statements I can see it work as designed in the terminal.
clock = 10
timeLeft = () ->
if clock > 0
clock--
console.log clock
else
console.log "That's All Folks"
Meteor.clearInterval(interval)
interval = Meteor.setInterval(timeLeft, 1000)
if Meteor.isClient
Template.timer.time = interval
If you want to update a value in handlebars you need to use Session so that its reactive, otherwise the Templating system won't be aware of when to update it in the ui. Also you passed the template a handler thats the handle instead of the timer value.
Using the below, I've used Session to pass this data through to handlebars.
clock = 10
timeLeft = ->
if clock > 0
clock--
Session.set "time", clock
console.log clock
else
console.log "That's All Folks"
Meteor.clearInterval interval
interval = Meteor.setInterval(timeLeft, 1000)
if Meteor.isClient
Template.timer.time = ->
Session.get "time"
Also in javascript in case anyone else wants this:
var clock = 10;
var timeLeft = function() {
if (clock > 0) {
clock--;
Session.set("time", clock);
return console.log(clock);
} else {
console.log("That's All Folks");
return Meteor.clearInterval(interval);
}
};
var interval = Meteor.setInterval(timeLeft, 1000);
if (Meteor.isClient) {
Template.registerHelper("time", function() {
return Session.get("time");
});
}
In essence you tell Session the time value, and when its updated it tells the templating system to redraw with the updated time value.
Related
Recently I updated from sinon 9 to sinon 14 which causes one of my tests to fail with the error Can't install fake timers twice on the same global object.. It looks like since version 12 it is not possible to call useFakeTimers multiple times to manage different clocks. What would be the alternative to achieve the same thing in sinon version 14?
t.test(`Skip calling the callback when the delay exceeds maxDelay`, t => {
t.plan(1);
const oneMinute = 60e3;
let rules = ['0 * * * * *']; // every minute
let timezone = null;
let maxDelay = 10;
let timerLag = 11;
let callback = spy();
let realClock = useFakeTimers({toFake: ['Date']});
let timerClock = useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'setImmediate', 'clearImmediate'] });
scheduleInterval(rules, timezone, maxDelay, callback);
realClock.tick(oneMinute + timerLag);
timerClock.tick(oneMinute);
t.equal(callback.callCount, 0);
realClock.restore();
timerClock.restore();
});
Using SwiftUI (or Combine) how might I set up a series of one or more events that are triggered by the (system) clock. Examples might include:
Every night at midnight,
On the hour,
Every fifteen minutes on the quarter hour,
Finally, on a slightly different note: On the 29th of February 2020 at 12:15.
An approximation is easily achieved by setting up a timer event that fires every second and then checking the hours/minutes/seconds, etc. but this seems very inefficient for events that may be many hours or days apart.
I'm looking for something that is closely synchronised to the actual system clock and fires off a single event at the required time rather than firing loads of events and having each one ask "Are we there yet?".
I would suggest the following:
DispatchQueue.global(qos: .background).async {
let isoDate = "2020-01-13T16:58:30+0000"
let dateFormatter = ISO8601DateFormatter()
let date = dateFormatter.date(from:isoDate)!
let t = Timer(fire: date, interval: 2, repeats: true) { timer in
print("fired")
}
let runLoop = RunLoop.current
runLoop.add(t, forMode: .default)
runLoop.run()
}
string to date conversion I used this answer to format the time correctly.
The example is in GMT.
documentation apple you can look up timer tolerance which can be adjusted if you need the timer to be very accurate.
interval is in seconds so this solution won't get more accurate than seconds
You might want to enable the Background Modes capability to go for the very long running timers. Never done that so I can't help here.
All your examples should work. I hope this helps!
I had to implement this feature too using Combine / SwiftUI : a Timer that would execute at start then every day, hour or minutes (for testing), here is my solution if it can be useful or improved :)
class PeriodicPublisher {
var periodicFormat: PeriodicFormat = .daily
init(_ format: PeriodicFormat = .daily) {
self.periodicFormat = format
}
// Must have an equatable for removeDuplicate
struct OutputDate: Equatable {
let compared: String
let original: String
init(_ comparedDatePart: String, _ originalDate: String) {
self.compared = comparedDatePart
self.original = originalDate
}
static func ==(lhs: OutputDate, rhs: OutputDate) -> Bool {
return lhs.compared == rhs.compared
}
}
enum PeriodicFormat {
case daily
case hourly
case minutely
func toComparableDate() -> String {
switch self {
case .daily:
return "yyyy-MM-dd"
case .hourly:
return "HH"
case .minutely:
return "mm"
}
}
}
func getPublisher() -> AnyPublisher<OutputDate, Never> {
let compareDateFormatter = DateFormatter()
compareDateFormatter.dateFormat = self.periodicFormat.toComparableDate()
let originalTimerDateFormatter = DateFormatter()
originalTimerDateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
var nowDate: Just<OutputDate> {
let comparedDate = compareDateFormatter.string(from: Date())
let originalDate = originalTimerDateFormatter.string(from: Date())
return Just(OutputDate(comparedDate, originalDate))
}
let timerDate = Timer.publish(every: 2.0, tolerance: 1.0, on: .main, in: .default, options: nil)
.autoconnect()
.map { dateString -> OutputDate in
return OutputDate(compareDateFormatter.string(from: dateString), originalTimerDateFormatter.string(from: dateString))
}
.eraseToAnyPublisher()
return Publishers.Merge(nowDate, timerDate)
.map { $0 }
.removeDuplicates()
.eraseToAnyPublisher()
}
}
How does it work ?
Every 2 seconds the scheduler issue current date (with Timer.publish()), this date is used to create a "OutputDate" holding two properties : one "comparable" part used to compare if something has changed and one "original" part so it can be useful for the consumer.
Comparable property is Timer's date formatted with toComparableDate given the provided configuration (.daily, .hourly, .minutely). Using "removeDuplicates" on this property allow to publish "OutputDate" only when this value changes. Every day or hour or minute.
Publishers.Merge is used to publish a value immediately after instantiation, otherwise nothing happens before the first Timer.publish(every). Here 2 seconds.
How to use it ?
You would use it with Combine like this :
PeriodicPublisher(.daily).getPublisher().sink { date in
print("Day has changed \(date.original)")
}
I have a signal producer, when it's terminated I would like to know if a value was sent, I only need the last one, seems so simple ...
let myProducer: SignalProducer<MyObject, MyError> = getMyProducer()
myProducer.on(terminated: {
// I need the last value here
// Or I need to know if value was never called
}).start()
I've tried to store the value in a local var :
let myProducer: SignalProducer<MyObject, MyError> = getMyProducer()
var myValue: MyObject?
myProducer.on(value: { value in
myValue = value
}, terminated: {
guard let value = myValue else {
// value was never called
return
}
// value was called
}).start()
But sometimes terminated is called while value has been called but myValue is still nil...
First, are you really sure that you want the terminated event?
Under normal conditions, an event stream ends with a completed event. Exceptions are failed when a failure has occurred and interrupted, when the observation was ended before the stream could complete normally (E.g. cancellation).
Second: Can your SignalProducer fail, and in the failure case, do you still want the last value sent before the failure?
If not, its as easy as using the take(last:) operator:
enum MyError: Error {
case testError
}
let (signal, input) = Signal<Int, MyError>.pipe()
let observer = Signal<Int, MyError>.Observer(
value: { print("value: \($0)") },
failed: { print("error: \($0)") },
completed: { print("completed") },
interrupted: { print("interrupted") }
)
signal
.take(last: 1)
.observe(observer)
input.send(value: 1) // Nothing printed
input.send(value: 2) // Nothing printed
input.send(value: 3) // Nothing printed
input.sendCompleted() // value 3 printed
I'm using a Signal here so I can manually send events to it just for demonstration, the same works for SignalProducer as well.
Note: If we send interrupted or a failed event, the last value 3 will not be sent because those to terminating events short circuit the normal flow.
If your SignalProducer can fail, and you still want to get the last value before the failure, you can use flatMapError to ignore the Error before the last operator:
signal
.flatMapError { _ in
return .empty
}
.take(last: 1)
.observe(observer)
my answer :
producer
.flatMapError { _ in SignalProducer<Value, NoError>.empty }
.collect()
startWithResult( { result in
case let .success(results):
done(with: results.last)
case let .failure(error):
() // should not happen as errors are flatmapped
})
We want to add some type of functionality that when a page takes longer than x seconds to load a warning is presented. We don't want that to throw a WaitTimeoutException, because the test can still execute cleanly, just longer than desired. We would still use the default timeout to throw our WaitTimeoutException after 20 seconds. This implies that x is less than 20. It's essentially a performance check on the page itself.
I've tried using the onLoad function:
void onLoad(Page previousPage) {
double warnSeconds = 0.001
LocalDateTime warnTime = LocalDateTime.now().plusMillis((int)(warnSeconds * 1000))
boolean warned = false
boolean pageReady = false
while(!warned && !pageReady) {
if(LocalDateTime.now() > warnTime) {
log.warn("${this.class.simpleName} took longer than ${warnSeconds} seconds to load")
warned = true
}
pageReady = js.exec('return document.readyState') == 'complete'
}
}
However:
"Sets this browser's page to be the given page, which has already been
initialised with this browser instance."
Any help would be great. Thanks.
______________________________________EDIT_______________________________________
Instead of using my own timer, used javascript window.performance. Now I'm looking to be able to access a variable in my test from my pages.
______________________________________EDIT_______________________________________
void onLoad(Page previousPage) {
def performance
//TODO system property page time
def pageTime = 8000
if (browser.driver instanceof InternetExplorerDriver) {
performance = js.exec('return JSON.stringify(window.performance.toJSON());')
} else {
performance = js.exec('return window.performance || window.webkitPerformance || window.mozPerformance ' +
'|| window.msPerformance;')
}
int time = performance['timing']['loadEventEnd'] - performance['timing']['fetchStart']
if (time > pageTime) {
String errorMessage = "${this.class.simpleName} took longer than ${pageTime} milliseconds " +
"to load. Took ${time} milliseconds."
log.error(errorMessage)
//TODO Soft Assert
}
}
New chunk of code to actually get the correct performance data instead of using my own timer. Now where I have //TODO Soft Assert, I have an object in my test that I want to access from my Page Object, but have no context. How can I get context?
With default view set to agendaWeek. If I load fullCalendar at 11:59PM the today day slot is not automatically updated after 12:00AM until I refresh the browser.
This is how I fixed it:
Call a function every 5 minutes (or any interval that suits your requirements)
$(function() {
var tInterval = 5*60*1000;
timelineInterval = window.setInterval(updateFcToday, tInterval); // Update timeline after every 5 minutes
});
Add a function like this to the page that contains your calendar:
function updateFcToday() {
var curTime = new Date();
if(curTime.getHours() == 0 && curTime.getMinutes() <= 5) // this five minutes is same interval that we are calling this function for. Both should be the same
{// the day has changed
var todayElem = $(".fc-today");
todayElem.removeClass("fc-today");
todayElem.removeClass("fc-state-highlight");
todayElem.next().addClass("fc-today");
todayElem.next().addClass("fc-state-highlight");
}
}