[Solved] Simple non-blocking delay


#1

Hey! I’ve run into some problems that i never imagined i could get stomped on.
So haxe has a timer library, great, except if i call a function it only delays the call and i cannot cancel it,
and it also keeps calling it after the delay.

I want to be able to call a function and if the given time has passed it gets called, but if i try to call it and the given time hasn’t passed yet nothing happens.

Should’ve been simple but i have no idea how to implement it correctly.
Any thoughts?


#2

Hello, haxe.Timer.delay returns with the Timer object so you can store it and cancel it anytime.

var t = Timer.delay(() -> trace("Hello World"), 5000);
Timer.delay(t.stop, 1000);

#3

So i tried what you suggested, but it still doesn’t cancel it and calls the function multiple times before the next delay.
I’m trying to use it as a delay between shots for a weapon with some fire rate between 1 and 60.
Here is how i tried to use it now:

public function shoot(){
     timer = Timer.delay(this.createchildp,Std.int(1000/firerate));       
}

And the first line of creating the bullet is to stop the timer:

function createchildp(){
    this.timer.stop();
    "create the bullet, give it a vector..."
}

#4

Timer.delay runs just once, in you situation you don’t need to call the stop function.

I think you call the shoot function multiple time which is a problem. Instead of a timer maybe you should check timestamps in your update/loop function like:

var lastShootTime = 0;
var firerate = 500;
var state = "idle"

public function shoot()
{
	state = "shoot"
	lastShootTime = Date.now().getTime();
}

public function update(d:Float)
{
	var now = Date.now().getTime();
	if (state == "shoot" && now - lastShootTime > firerate)
	{
		lastShootTime = now;
		createchildp();
	}
}

#5

yes that works way better, thank you :grin: