Timers in AngelScript

#include "AngelScript/addons/scriptarray/scriptarray.h"
#include "AngelScript/addons/scriptdictionary/scriptdictionary.h"
#include "AngelScript/addons/datetime/datetime.h"

void main()
{
    // Timers represent a single event in the future. You
    // tell the timer how long you want to wait, and it
    // provides a callback that will be executed at that
    // time. This timer will wait 2 seconds.
    Timer@ timer1 = Timer();
    timer1.setInterval(2000);
    timer1.setOnce(true);
    timer1.add(@Timer1Callback);
    timer1.start();

    // The Timer1Callback function will be called when the timer fires.
    // We'll use a while loop to simulate waiting for the timer.
    while (!timer1Fired)
    {
        // Simulating other work
    }
    print("Timer 1 fired\n");

    // If you just wanted to wait, you could have used
    // sleep(). One reason a timer may be useful is
    // that you can cancel the timer before it fires.
    // Here's an example of that.
    Timer@ timer2 = Timer();
    timer2.setInterval(1000);
    timer2.setOnce(true);
    timer2.add(@Timer2Callback);
    timer2.start();

    // Stop the timer before it has a chance to fire
    timer2.stop();
    print("Timer 2 stopped\n");

    // Give the timer2 enough time to fire, if it ever
    // was going to, to show it is in fact stopped.
    sleep(2000);
}

bool timer1Fired = false;

void Timer1Callback()
{
    timer1Fired = true;
}

void Timer2Callback()
{
    print("Timer 2 fired\n");
}

In AngelScript, we don’t have built-in timer functionality like in some other languages. Instead, we’re using a hypothetical Timer class that provides similar functionality. Here’s how it works:

  1. We create a Timer object and set its interval (in milliseconds).
  2. We set the timer to fire only once with setOnce(true).
  3. We add a callback function that will be called when the timer fires.
  4. We start the timer with start().

For the first timer, we use a while loop to simulate waiting for the timer to fire. In a real application, you would typically use this time to do other work.

For the second timer, we demonstrate how to stop a timer before it fires. We create and start the timer, then immediately stop it.

Note that AngelScript doesn’t have native support for concurrency like goroutines in Go. In a real application, you’d need to implement your own threading mechanism or use one provided by the host application.

To run this script, you would need to have the AngelScript engine set up with the necessary add-ons (ScriptArray, ScriptDictionary, and DateTime). The exact method of execution would depend on how AngelScript is integrated into your application.

This example demonstrates the concept of timers in AngelScript, showing how to create, start, and stop timers, as well as how to use callback functions with timers.