I have this script for countdown I wanted it to start as soon as the page loads (ideally i wanted it to run continuously since it is repeating in intervals).
when I call any function such as [startCountdown()] or [ countdown.start($('#countdown_clock').val());] I keep getting the same error [Uncaught ReferenceError: countdown is not defined]
here is the whole function
window.onload = function mainCountdown() {
var countdown = Tock({
countdown: true,
interval: 250,
callback: function () {
// console.log(countdown.lap() / 1000);
$('#countdown_clock').val(countdown.msToTime(countdown.lap()));
// countdown.start($('#countdown_clock').val());
},
complete: function () {
// console.log('end');
// alert("Time's up!");
repeatCountdown();
console.log('alarm');
}
});
$('#startCountdown').on('click', function () {
countdown.start($('#countdown_clock').val());
});
$('#pauseCountdown').on('click', function () {
countdown.pause();
});
$('#stopCountdown').on('click', function () {
countdown.stop();
});
$('#resetCountdown').on('click', function () {
countdown.stop();
$('#countdown_clock').val('00:10');
});
function repeatCountdown() {
countdown.stop();
$('#countdown_clock').val('00:10');
countdown.start($('#countdown_clock').val());
}
function startCountdown(){
countdown.start($('#countdown_clock').val());
}
}
How can I start the countdown without any button events.
Thank you in advance
You seem to have a few syntax issues that might be causing the problem. First, I'd call the window load event like this:
$(window).load(function () {
// functions, etc here
});
Then, inside the window load event, you can create your timer like this:
var countdown = new Tock(...
You were missing the 'var' and 'new' keywords. You might want to revisit the Tock documentation to make sure everything else was correct, too.
Related
I have a problem with runOnJS in my swipe function.
All the time Im gets error:
java.lang.RuntimeException: Tried to synchronously call function {w} from a different thread.
Im gets the error in panGesture function when its called finishAnimation.
Code is here:
https://pastebin.com/YaQs4bN6
You're calling "finishAnimation" from the onEnd callback. That could be a problem, since finishAnimation isn't a worklet.
So you have two options:
finishAnimation can be marked with the "worklet" keyword
const finishAnimation = (swipe_down) => {
"worklet";
// This logger can't be here anymore since it's a JS function
// Logger.bool(swipe_down, { swipe_down });
if (swipe_down) {
offset.value = withTiming(height.value, { duration: 100 }, () =>
runOnJS(props.onSwipeComplete)()
);
} else {
offset.value = withTiming(0, { duration: 200 });
}
};
finishAnimation can be called async on the JS Thread:
runOnJS(finishAnimation)(
e.velocityY > swipeOutVelocity || offset.value > calculateThreshold()
);
Hopefully it's going to work.
As you are using Reanimated 2. you can add the Worklet directive to onSwipeComplete then you can run this function in both UI and JavaScript` threads.
More about worklet here - https://docs.swmansion.com/react-native-reanimated/docs/fundamentals/worklets
I'm making an HTML5 game with melonjs.
One of my entitie (called ET1) needs to listen on 2 events : pointerup & pointerdown. My events are registered in my game.js file, as follow :
me.input.registerPointerEvent("pointerup", me.game.viewport, function (event) {
me.event.publish("pointerup", [ event ]);
});
me.input.registerPointerEvent("pointerdown", me.game.viewport, function (event) {
me.event.publish("pointerdown", [ event ]);
});
In my ET1 entitie, i'm listening for both of the events :
this.handler = me.event.subscribe("pointerup", function (event) {
...
});
this.handlerDown = me.event.subscribe("pointerdown", function (event) {
...
});
When the pointerdown event is triggered, i'm updating a local property, and if this property reach a certain value, i would like to trigger the pointerup event manually from the update method :
update : function (dt) {
this.handler = me.event.subscribe("pointerup", function (event) {
...
});
this.handlerDown = me.event.subscribe("pointerdown", function (event) {
...
});
localVar++;
if(localVar > 10){
// trigger pointerup event
}
}
I now it's possible with event.publish from withing a registerPointerEvent callback, but i hav no idea how to do this from the entitie update method.
Any idea ?
if you don't do anything with the Event object, you can just manually publish the "pointerup" message, same way as you subscribe to them :
me.event.publish("pointerup", [{}]);
{} here meaning to replace the Event object, although you could pass it as well since it's available in the global scope
We are using dojo without pagination and showing all records at once. We need to call a java script method when the entire grid has been rendered completely, so that the grid rows and cell can be used for DOM manipulation.
I am trying following code, but its not working.
aspect.after(grid,"dgrid-refresh-complete",function(){
});
grid.on("dgrid-refresh-complete", function(event){
});
dgrid-refresh-complete is implemented specifically in OnDemandList and Pagination. If you're using the SingleQuery mixin instead (as in the tutorial for 0.3 or 0.4), it should be feasible to institute the same kind of event as follows:
var self = this;
// existing code from refresh...
// when(...) (via dojo/when) should only be necessary here for dgrid 0.3
var promise = when(this._trackError(/* existing code from refresh */));
promise.then(function () {
on.emit(self.domNode, 'dgrid-refresh-complete', {
bubbles: true,
cancelable: false,
grid: self
});
});
return promise;
So, for example, in 0.3, SingleQuery's refresh method would look like this:
refresh: function () {
var self = this;
// First defer to List#refresh to clear the grid's
// previous content
this.inherited(arguments);
if (!this.store) {
return;
}
var promise = when(this._trackError(function () {
var queryOptions = self.get('queryOptions'),
results = self.store.query(
self.query, queryOptions);
return self.renderArray(
results, null, queryOptions);
}));
promise.then(function () {
on.emit(self.domNode, 'dgrid-refresh-complete', {
bubbles: true,
cancelable: false,
grid: self
});
});
return promise;
}
How can I complete function in init before call ready method. My code:
WinJS.Namespace.define("Data", {
source: ""
});
var page = WinJS.UI.Pages.define("/html/page.html", {
init: function (element, options) {
createDataSoucre();
},
ready: function () {
document.getElementById("result").innerHTML = Data.source;
}
});
function createDataSoucre() {
//blah blah (calculate thousands of calculations)
Data.source = result;
}
When I run, page doesn't render "result" tag. I try use promises but it doesn't work for me:
init: function (element, options) {
return new WinJS.Promise.as(createDataSoucre());
}
Thanks for your time.
I tried your code in a simple test project as follows:
(function () {
"use strict";
WinJS.Namespace.define("Data", {
source: ""
});
function createDataSource() {
Data.source = "<ul><li>Item 1</li><li>Item2</li><li>Item3</li></ul>";
}
WinJS.UI.Pages.define("/pages/home/home.html", {
init: function (element, options) {
createDataSource();
},
ready: function (element, options) {
document.getElementById("result").innerHTML = Data.source;
}
});
})();
Everything works as expected, with the bullet list appearing on the page.
However, I believe you're asking how to make your createDataSource function asynchronous in itself, so that it can do your "thousands of calculations" off the UI thread and produce a promise that the init function can return. This way, the page loading process will wait upon the completion of those calculations.
What's needed here is to use new WinJS.Promise rather than WinJS.Promise.as. The as method just wraps a value in a promise so that the value is send to any completed handler you attach, but doesn't create an async function automatically. That's something you have to do.
Let me provide an example from Appendix A of my free ebook, Programming Windows Store Apps with HTML, CSS, and JavaScript, Second Edition, where Chapter 3 and Appendix A go into all the details about promises. Here's a function that does a long series of calculations using setImmediate to break up the work on the UI thread. (You could also use web workers to put the work on another thread, or use a WinRT component--but I'll leave it to my book to talk about those subjects, which is in Chapter 18 in the section "Implementing Asynchronous Methods").
function calculateIntegerSum(max, step) {
//The WinJS.Promise constructor's argument is a function that receives
//dispatchers for completed, error, and progress cases.
return new WinJS.Promise(function (completeDispatch, errorDispatch, progressDispatch) {
var sum = 0;
function iterate(args) {
for (var i = args.start; i < args.end; i++) {
sum += i;
};
if (i >= max) {
//Complete--dispatch results to completed handlers
Data.source = "Sum is <em>" + sum + "</em>";
completeDispatch(sum);
} else {
//Dispatch intermediate results to progress handlers
progressDispatch(sum);
setImmediate(iterate, { start: args.end, end: Math.min(args.end + step, max) });
}
}
setImmediate(iterate, { start: 0, end: Math.min(step, max) });
});
}
You can do something similar for your own process. The key here is that when your process is complete, you have to call the completeDispatch function that's given to your initializer. In the code above I'm also putting the result into Data.source.
With such a method, your createDataSource function can look like this:
function createDataSource() {
return calculateIntegerSum(100000, 2);
}
Because calculateIntegerSum returns a promise and is implemented to be async, createDataSource will return a promise that you can return from init:
init: function (element, options) {
return createDataSource();
},
I tried this out in a project and it works just fine, with the page loading waiting upon the calculations to complete.
I have the following:
casper.then(function addToBag(){
this.evaluate(function (){
//register sub method - then emit custom event
mns.msg.sub("/ajax/success/addToCart" + $("[name=productCode]").val(), function (response) {
casper.emit('addToCart.loaded');
});
//trigger add to cart click
$('.product-selection input[type=submit]').click();
});
});
The click trigger activates the emit, inside the event function:
casper.on("addToCart.loaded", function checkAddToCartResponse(){
console.log("Added");
test.assert(true,'Add to cart successful');
}),
However, it doesn't seem to run - is this the correct way of running a test when an event has finished?
The event is not emitted because there is no casper instance inside the page context (inside the evaluate context).
You would need to set some flag that the event was emitted.
casper.then(function addToBag(){
this.evaluate(function (){
//register sub method - then emit custom event
window.casperEventEmitted = null;
mns.msg.sub("/ajax/success/addToCart" + $("[name=productCode]").val(), function (response) {
window.casperEventEmitted = 'addToCart.loaded';
});
//trigger add to cart click
$('.product-selection input[type=submit]').click();
});
});
// wait here
and then wait for the event to be set
var timeout = 10000; // msec, some sensible timeout for your event
casper.waitFor(function check() {
return this.getGlobal('casperEventEmitted') == 'addToCart.loaded';
}, function then() {
return this.evaluate(function() {
window.casperEventEmitted = null; // reset for next time
});
this.test.pass("Event triggered");
}, function onTimeout(){
this.test.fail("Event triggered");
}, timeout);
Of course it would be nicer to manage the events in a queue and not as a single string.
The good thing is that there is no break out from the control flow as it would happen with a custom event like in the case of the other answer.
Use inside the evaluate callback:
console.log("casper-event:add:[1234]");
then can do it like this (not tested):
casper.on('remote.message', function(msg) {
if(msg.indexOf("casper-event:" == 0))
{
var event = msg.replace(/^casper-event:/, '').replace(/:.*$/, '');
var result = JSON.parse(msg.replace(/^casper-event:.*?:/, ''));
this.emit(event, result);
}
});
casper.on('add'........