How do you wait one second before completing an action in HaxeFlixel? - haxe

I'm looking to find a way to have HaxeFlixel wait one second before an action, but FlxTimer isn't being useful. Thanks.

Create a timer variable and assign a callback function. This code will wait for one second before running the sayHello() function:
var timer:FlxTimer = new FlxTimer().start(1, sayHello);
...
private function sayHello(timer:FlxTimer)
{
trace("Hello!!");
}

Related

How to have a block of code run then loop it every few minutes

I want to have a block of code run right away and then loop it every few minutes. I was using setInterval but it waits the amount of time you give it and then runs the block of code and loops.
So you have to define that code inside function then call that function first then add set interval code and pass this function to it
function s () {}
s();
setInterval(s, 100)
Or you can use set timeOut inside this function and run it recursively, that's will be good in asynchronous calls you can use await to wait for response then run this function again after timeout, because setInterval will cause overlap in that case.
async function s() {
let a = await calldb;
setTimeout (s,1000)
}
s();

while loop in sync function in node js [duplicate]

The following example is given in a Node.js book:
var open = false;
setTimeout(function() {
open = true
}, 1000)
while (!open) {
console.log('wait');
}
console.log('open sesame');
Explaining why the while loop blocks execution, the author says:
Node will never execute the timeout callback because the event loop is
stuck on this while loop started on line 7, never giving it a chance
to process the timeout event!
However, the author doesn't explain why this happens in the context of the event loop or what is really going on under the hood.
Can someone elaborate on this? Why does node get stuck? And how would one change the above code, whilst retaining the while control structure so that the event loop is not blocked and the code will behave as one might reasonably expect; wait
will be logged for only 1 second before the setTimeout fires and the process then exits after logging 'open sesame'.
Generic explanations such as the answers to this question about IO and event loops and callbacks do not really help me rationalise this. I'm hoping an answer which directly references the above code will help.
It's fairly simple really. Internally, node.js consists of this type of loop:
Get something from the event queue
Run whatever task is indicated and run it until it returns
When the above task is done, get the next item from the event queue
Run whatever task is indicated and run it until it returns
Rinse, lather, repeat - over and over
If at some point, there is nothing in the event queue, then go to sleep until something is placed in the event queue or until it's time for a timer to fire.
So, if a piece of Javascript is sitting in a while() loop, then that task is not finishing and per the above sequence, nothing new will be picked out of the event queue until that prior task is completely done. So, a very long or forever running while() loop just gums up the works. Because Javascript only runs one task at a time (single threaded for JS execution), if that one task is spinning in a while loop, then nothing else can ever execute.
Here's a simple example that might help explain it:
var done = false;
// set a timer for 1 second from now to set done to true
setTimeout(function() {
done = true;
}, 1000);
// spin wait for the done value to change
while (!done) { /* do nothing */}
console.log("finally, the done value changed!");
Some might logically think that the while loop will spin until the timer fires and then the timer will change the value of done to true and then the while loop will finish and the console.log() at the end will execute. That is NOT what will happen. This will actually be an infinite loop and the console.log() statement will never be executed.
The issue is that once you go into the spin wait in the while() loop, NO other Javascript can execute. So, the timer that wants to change the value of the done variable cannot execute. Thus, the while loop condition can never change and thus it is an infinite loop.
Here's what happens internally inside the JS engine:
done variable initialized to false
setTimeout() schedules a timer event for 1 second from now
The while loop starts spinning
1 second into the while loop spinning, the timer is ready to fire, but it won't be able to actually do anything until the interpreter gets back to the event loop
The while loop keeps spinning because the done variable never changes. Because it continues to spin, the JS engine never finishes this thread of execution and never gets to pull the next item from the event queue or run the pending timer.
node.js is an event driven environment. To solve this problem in a real world application, the done flag would get changed on some future event. So, rather than a spinning while loop, you would register an event handler for some relevant event in the future and do your work there. In the absolute worst case, you could set a recurring timer and "poll" to check the flag ever so often, but in nearly every single case, you can register an event handler for the actual event that will cause the done flag to change and do your work in that. Properly designed code that knows other code wants to know when something has changed may even offer its own event listener and its own notification events that one can register an interest in or even just a simple callback.
This is a great question but I found a fix!
var sleep = require('system-sleep')
var done = false
setTimeout(function() {
done = true
}, 1000)
while (!done) {
sleep(100)
console.log('sleeping')
}
console.log('finally, the done value changed!')
I think it works because system-sleep is not a spin wait.
There is another solution. You can get access to event loop almost every cycle.
let done = false;
setTimeout(() => {
done = true
}, 5);
const eventLoopQueue = () => {
return new Promise(resolve =>
setImmediate(() => {
console.log('event loop');
resolve();
})
);
}
const run = async () => {
while (!done) {
console.log('loop');
await eventLoopQueue();
}
}
run().then(() => console.log('Done'));
Node is a single serial task. There is no parallelism, and its concurrency is IO bound. Think of it like this: Everything is running on a single thread, when you make an IO call that is blocking/synchronous your process halts until the data is returned; however say we have a single thread that instead of waiting on IO(reading disk, grabbing a url, etc) your task continues on to the next task, and after that task is complete it checks that IO. This is basically what node does, its an "event-loop" its polling IO for completion(or progress) on a loop. So when a task does not complete(your loop) the event loop does not progress. To put it simply.
because timer needs to comeback and is waiting loop to finish to add to the queue, so although the timeout is in a separate thread, and may indeed finsihed the timer, but the "task" to set done = true is waiting on that infinite loop to finish
var open = false;
const EventEmitter = require("events");
const eventEmitter = new EventEmitter();
setTimeout(function () {
open = true;
eventEmitter.emit("open_var_changed");
}, 1000);
let wait_interval = setInterval(() => {
console.log("waiting");
}, 100);
eventEmitter.on("open_var_changed", () => {
clearInterval(wait_interval);
console.log("open var changed to ", open);
});
this exemple works and you can do setInterval and check if the open value changed inside it and it will work

How can I mitigate a race condition between the UI thread and a DispatcherTimer.Tick event?

I believe I have a race condition in this code sample but am unsure how to mitigate it.
My scenario is that XAsync() always runs on the UI thread. Within XAsync(), I set m_importantMemberVariable and then start a timer; there's a 1 second delay before the timer fires.
My concern is the timer's tick event calls a method on m_importantMemberVariable. However, in the 1 second interval between starting the timer and Tick firing, XAsync() could be called again and overwrite m_importantMemberVariable.
Code example:
task<void> BobViewModel::XAsync()
{
return create_task(CreateSomethingAsync())
.then([this](SomethingAsync^ aThing)
{
this->m_importantMemberVariable = aThing;
OnPropertyChanged("ImportantMemberVariable");
// Timer has 1 second delay.
this->m_myDispatcherTimer->Start();
}, task_continuation_context::use_current())
.then([activity](task<void> result)
{
// more continuations...
});
}
void BobViewModel::OnTimerTick(Object^, Object^)
{
// Stopping the timer and detaching the event handler
// so timer only fires once.
m_myDispatcherTimer->Stop();
m_myDispatcherTimer->Tick -= m_impressionTimerToken;
m_myDispatcherTimer = { 0 };
// * Possible race condition *
m_importantMemberVariable->DoImportantThing();
}
Question: Assuming I'm correct about a race condition, is there a way to mitigate it?
My understanding is the tick event would fire on the UI thread so synchronization primitives won't help (as the UI thread would already have access).
All your operations are on the UI thread, so they've already been serialized (synchronized) for you. A simple flag will suffice:
bool m_busy; // set to false in constructor
task<void> BobViewModel::XAsync()
{
if (m_busy)
return;
m_busy = true;
// the rest of your code...
}
void BobViewModel::OnTimerTick(Object^, Object^)
{
m_busy = false;
// the rest of your code...
}
Just make sure you handle any exceptions such that you set m_busy back to false if something goes horribly wrong.
The answer to this question suggests using compare_exchange_strong with a std::atomic to ensure only one thread executes a function at a time. The problems with that approach, for this question, are:
1. The DispatcherTimer Tick event fires outside of the task continuation block, and can fire after the continuation completes.
2. A constraint on this problem is for the timer to only fire once.
Some alternative solutions are:
Use compare_exchange_strong but replace DispatcherTimer with create_delayed_task
Assuming the work doesn't have to happen on the UI thread, you can use create_delayed_task to delay work within a task continuation.
task<void>
BobViewModel::UseImportantVariableAsync(
Object^ importantVariable
)
{
return create_delayed_task(
std::chrono::milliseconds(1000),
[importantVariable]()
{
importantMemberVariable->DoImportantThing();
});
}
Then, from the task continuation, simply:
return UseImportantVariableAsync(m_importantMemberVariable);
Use a lambda for the DispatcherTimer's Tick event and capture 'aThing' from the question's example (instead of referencing the member variable in the handler). To only fire the timer once, assign the DispathcerTimer.Tick handler within a std::call_once block so only the first caller gets to do it.

Node - Run code after return statement

Is there any way to run a block of code after the return of a function in node js?
Something like this:
function f() {
#do stuff
#return result
#do more stuff
}
No, there is no way to do that in the way that you show. return exits from the containing function and statements immediately after the return statement do not execute (in fact they are dead code).
(Per your comments) If what you're really trying to do is to execute something "out of band" that the rest of the function (including the return value) does not depend upon, you could schedule that code to run later. For example, you could use setTimeout(), process.nextTick() or setImmediate().
function f() {
// do stuff
setTimeout(function() {
// do some stuff here that will execute out of band
// after this function returns
}, 0);
return someVal;
}
There are legit uses for things like this where you want to execute something soon, but you don't want it to get in the way of the current operation. So, you'd essentially like to queue it to execute when the current activity is done.
The answer is No. After you return the function will stop execution. You can consider using a better flow control to run the code like Async/Await or Promise
You use the return statement to stop execution of a function and return the value of expression. according to the following doc
https://learn.microsoft.com/en-us/scripting/javascript/reference/return-statement-javascript

Sleeping in action script 2 using getTimer() method

How can I correctly perform something like sleep function using getTimer()? I need to do an action every 15 seconds. The code below doesn't work. I compile it with mtasc compiler on Linux.
class Tuto
{
static var lastMsg = 0;
static var msgInt = 15000;
static function main(mc)
{
if(getTimer() > lastMsg + msgInt)
{
trace("something");
lastMsg = getTimer();
}
}
}
The main instruction will be executed just once. You have to build some kind of loop or rely on the tick events sent by the player to execute your code continuously.
The basic options are:
while (true) { doSomething() }
this will execute forever, but remember that the flashplayer is single threaded so while that runs everything else will be frozen, UI and user inputs included. this is only "good" if you are building some heavy-processing tool that has no need of interacting with the user.
setInterval(doSomething, 15000)
this creates an interval that will call your function every X milliseconds. This is the simplest option and probably what you're looking for.
addEventListener(Event.ENTER_FRAME, doSomething)
this registers a listener for the ENTER_FRAME event of the Flash Player, which will be dispatched 30 times per second (by default). Inside that function you can check the current time with getTimer() and decide if it's time to execute your logic.

Resources