How to put a DELAY in an FADEIN - delay

So, I've got this:
$('header').fadeIn(1000, function() {
// Animation complete
});
$('#intro').fadeIn(3000, function() {
// Animation complete
});
And now I want the second one to come in later, so with a delay. But where in the code do I put this?
EDIT: Got it, thanks!

If you want to start the second animation after the first one, you should do this
$('header').fadeIn(1000, function() {
$('#intro').fadeIn(3000, function() {
// Animation complete
});
});

jQuery maintains a queue of effects per element. You are animating 2 elements so they will fire simultaneously.
More info: http://api.jquery.com/queue/
You can nest the functions but that's going to get difficult if you want 10 effects.
Here's a good solution:
https://stackoverflow.com/a/11354378/907253

Related

Make an event handler seamless?

I have written an event handler under Excel online add-in. It is activated by a button activate, then when a user clicks on another cell or range, the address will be written on a text area myTextArea. The whole thing works.
However, once a new cell is selected, a green loading symbol is shown near the focus; WORKING... is shown on the bottom of Excel; it takes almost 0.5 second.
I am just surprised that it takes time for such a simple action. Does anyone know if it is possible to make this event hander faster? Otherwise, is there any other mean than event handling to make this seamless?
(function() {
"use strict";
Office.initialize = function(reason) {
$(document).ready(function() {
app.initialize();
$('#activate').click(addSelectionChangedEventHandler);
});
}
;
function addSelectionChangedEventHandler() {
Office.context.document.addHandlerAsync(Office.EventType.DocumentSelectionChanged, MyHandler);
}
function MyHandler(eventArgs) {
doStuffWithNewSelection();
}
function doStuffWithNewSelection() {
Excel.run(function(ctx) {
var selectedRange = ctx.workbook.getSelectedRange();
selectedRange.load(["address"]);
return ctx.sync().then(function() {
write(selectedRange.address)
})
}).then(function() {
console.log("done");
}).catch(function(error) {
...
});
}
function write(message) {
document.getElementById("myTextarea").value = message;
}
})();
What you're seeing is network lag. The selection changed event -- once registered -- originates on the server, and triggers the code if Office.js that fires your event handler. Your event handler, in turn, creates a local request for getting the selection Range object and its address, sends it over to the server as part of ctx.sync(), and then waits to hear back from the server before firing the .then.
There's not anything you can do to optimize this flow -- you will pay a pretty high per-transaction cost on Excel Online, and event handlers only add one extra step to that cost. On the other hand, the good news is that the Excel.run/ctx-based model does allow you to batch multiple requests into one, drastically reducing the number of roundtrips that would otherwise be required. That is, fetching the values of 10 different ranges is almost identical in speed to fetching just one; whereas it would be 10 times more expensive if each call were made individually.
Hope this helps!
~ Michael Zlatkovsky, developer on Office Extensibility team, MSFT

Sprite movement stutters a lot randomly

I have a sprite and I set its y velocity to 200 so that it moves down.
The sprite moves perfectly fine except that sometimes it stutters a lot. The other times it is silky smooth. Its like the fps drops to 20.
How do I stop this stuttering?
Below is my code and you can try it live here
var SimpleGame = (function () {
function SimpleGame() {
this.game = new Phaser.Game(800, 400, Phaser.AUTO, 'content', { preload: this.preload, create: this.create, update: this.update });
}
SimpleGame.prototype.preload = function () {
this.game.load.image('logo', 'Sprites/icon.png');
};
SimpleGame.prototype.create = function () {
//Create Sprite
this.speed = 133;
this.game.stage.backgroundColor = 0xffffff;
this.logo = this.game.add.sprite(this.game.world.centerX, this.game.world.centerY, 'logo');
this.logo.position.set(200, 50);
this.game.physics.arcade.enable(this.logo);
//Set velocity
this.logo.body.velocity.y = this.speed;
};
return SimpleGame;
})();
window.onload = function () {
var game = new SimpleGame();
};
I am not getting the stuttering myself. So, try loading it with other computers, find friends with different levels of computers, to make sure that it isn't a local client-side problem. If it is, then check your computers firewall settings any antivirus that may be stopping a process which will slow down your game.
If it is a server-side problem- firstly, try to condense your code and the memory used. Use local variables instead of global ones, don't pass too many function arguments (If you are using a lot of function arguments then you are filling up the Stack and that may be causing the lag).
Also check your server. I don't know what web server you are using so I don't really know your specs on this, but I may be able to help. Does Phaser use too much memory for your webserver? Small Webservers are designed purely for small websites so by using a lot of JS (which Phaser does ,look in Phaser.min!) you may be using too much memory on your server. Maybe a bigger subscription?
I hope I've helped.

How to forcibly keep a Node.js process from terminating?

TL;DR
What is the best way to forcibly keep a Node.js process running, i.e., keep its event loop from running empty and hence keeping the process from terminating? The best solution I could come up with was this:
const SOME_HUGE_INTERVAL = 1 << 30;
setInterval(() => {}, SOME_HUGE_INTERVAL);
Which will keep an interval running without causing too much disturbance if you keep the interval period long enough.
Is there a better way to do it?
Long version of the question
I have a Node.js script using Edge.js to register a callback function so that it can be called from inside a DLL in .NET. This function will be called 1 time per second, sending a simple sequence number that should be printed to the console.
The Edge.js part is fine, everything is working. My only problem is that my Node.js process executes its script and after that it runs out of events to process. With its event loop empty, it just terminates, ignoring the fact that it should've kept running to be able to receive callbacks from the DLL.
My Node.js script:
var
edge = require('edge');
var foo = edge.func({
assemblyFile: 'cs.dll',
typeName: 'cs.MyClass',
methodName: 'Foo'
});
// The callback function that will be called from C# code:
function callback(sequence) {
console.info('Sequence:', sequence);
}
// Register for a callback:
foo({ callback: callback }, true);
// My hack to keep the process alive:
setInterval(function() {}, 60000);
My C# code (the DLL):
public class MyClass
{
Func<object, Task<object>> Callback;
void Bar()
{
int sequence = 1;
while (true)
{
Callback(sequence++);
Thread.Sleep(1000);
}
}
public async Task<object> Foo(dynamic input)
{
// Receives the callback function that will be used:
Callback = (Func<object, Task<object>>)input.callback;
// Starts a new thread that will call back periodically:
(new Thread(Bar)).Start();
return new object { };
}
}
The only solution I could come up with was to register a timer with a long interval to call an empty function just to keep the scheduler busy and avoid getting the event loop empty so that the process keeps running forever.
Is there any way to do this better than I did? I.e., keep the process running without having to use this kind of "hack"?
The simplest, least intrusive solution
I honestly think my approach is the least intrusive one:
setInterval(() => {}, 1 << 30);
This will set a harmless interval that will fire approximately once every 12 days, effectively doing nothing, but keeping the process running.
Originally, my solution used Number.POSITIVE_INFINITY as the period, so the timer would actually never fire, but this behavior was recently changed by the API and now it doesn't accept anything greater than 2147483647 (i.e., 2 ** 31 - 1). See docs here and here.
Comments on other solutions
For reference, here are the other two answers given so far:
Joe's (deleted since then, but perfectly valid):
require('net').createServer().listen();
Will create a "bogus listener", as he called it. A minor downside is that we'd allocate a port just for that.
Jacob's:
process.stdin.resume();
Or the equivalent:
process.stdin.on("data", () => {});
Puts stdin into "old" mode, a deprecated feature that is still present in Node.js for compatibility with scripts written prior to Node.js v0.10 (reference).
I'd advise against it. Not only it's deprecated, it also unnecessarily messes with stdin.
Use "old" Streams mode to listen for a standard input that will never come:
// Start reading from stdin so we don't exit.
process.stdin.resume();
Here is IFFE based on the accepted answer:
(function keepProcessRunning() {
setTimeout(keepProcessRunning, 1 << 30);
})();
and here is conditional exit:
let flag = true;
(function keepProcessRunning() {
setTimeout(() => flag && keepProcessRunning(), 1000);
})();
You could use a setTimeout(function() {""},1000000000000000000); command to keep your script alive without overload.
spin up a nice repl, node would do the same if it didn't receive an exit code anyway:
import("repl").then(repl=>
repl.start({prompt:"\x1b[31m"+process.versions.node+": \x1b[0m"}));
I'll throw another hack into the mix. Here's how to do it with Promise:
new Promise(_ => null);
Throw that at the bottom of your .js file and it should run forever.

Difference b/w event.on() and event.once() in nodejs

I'm testing the plus_one app, and while running it, I just wanted to clarify my concepts on event.once() and event.on()
This is plus_one.js
> process.stdin.resume();
process.stdin.on('data',function(data){
var number;
try{
number=parseInt(data.toString(),10);
number+=1;
process.stdout.write(number+"\n");
}
catch(err){
process.stderr.write(err.message+"\n");
}
});
and this is test_plus_one.js
var spawn=require('child_process').spawn;
var child=spawn('node',['plus_one.js']);
setInterval(function(){
var number=Math.floor(Math.random()*10000);
child.stdin.write(number+"\n");
child.stdout.on('data',function(data){
console.log('child replied to '+number+' with '+data);
});
},1000);
I get few maxlistener offset warning while using child.stdin.on() but this is not the case when using child.stdin.once(), why is this happening ?
Is it because child.stdin is listening to previous inputs ? but in that case maxlistener offset should be set more frequently, but its only happening for once or twice in a minute.
Using EventEmitter.on(), you attach a full listener, versus when you use EventEmitter.once(), it is a one time listener that will detach after firing once. Listeners that only fire once don't count towards the max listener count.
According to the latest official docs https://nodejs.org/api/events.html#events_eventemitter_defaultmaxlisteners. The .once() listener does count to the maxlisteners.
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
// do stuff
emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});

Make jPlayer stay at end of track

As demonstrated in the standard jPlayer demo, when the track ends, the player resets time to zero. Is there any way to make it stay at the end of the track?
Use the ended() event in conjunction with the playHead method to keep the play head at the end when it ends.
Modifying the example, here's what I got:
$(document).ready(function() {
$("#jquery_jplayer_1").jPlayer({
ready: function(event) {
$(this).jPlayer("setMedia", {
mp3: "http://www.jplayer.org/audio/mp3/TSP-01-Cro_magnon_man.mp3",
oga: "http://www.jplayer.org/audio/ogg/TSP-01-Cro_magnon_man.ogg"
});
},
swfPath: "http://www.jplayer.org/2.1.0/js",
supplied: "mp3, oga",
ended : function(){
console.log("ended");
$(this).jPlayer("playHead",100);
}
});
});
​
JSFiddle: http://jsfiddle.net/wjsKa/2/
Reference: http://jplayer.org/latest/developer-guide/
jPlayer is opensource, so you can tweak code as you desire. I suggest getting jquery.jplayer sources and removing lines 973 and 974 from jquery.jplayer.js. Then you just save your own copy and compress it if you desire to do so.
Or you can play around with _updateInterface method so it doesn't move seek bar when called from "ended" event handler.
Sorry for incomplete answer, can't test it right now.

Resources