Tickers in OpenSCAD

Tickers are used when you want to perform an action repeatedly at regular intervals. Here’s an example of a ticker that ticks periodically until we stop it.

use <MCAD/time.scad>

function create_ticker(interval) = [0, interval];

function is_ticker_active(ticker) = ticker[0] == 0;

function update_ticker(ticker) =
    is_ticker_active(ticker) ?
        [ticker[1], ticker[1]] :
        [ticker[0] - 1, ticker[1]];

function tick(ticker) =
    is_ticker_active(ticker) ?
        let(new_ticker = update_ticker(ticker))
        concat([1], new_ticker) :
        concat([0], ticker);

module simulate_ticker() {
    ticker = create_ticker(500);
    total_time = 1600;
    
    for (t = [0 : 100 : total_time]) {
        result = tick(ticker);
        if (result[0] == 1) {
            echo(str("Tick at ", t, "ms"));
        }
        ticker = [result[1], result[2]];
    }
    
    echo("Ticker stopped");
}

simulate_ticker();

In this OpenSCAD implementation, we simulate a ticker using functions and a loop. The create_ticker function initializes a ticker with a given interval. The tick function simulates a tick event and updates the ticker state.

The simulate_ticker module runs the simulation for 1600 milliseconds, printing “Tick at” messages at approximately 500ms intervals.

When we run this program, the ticker should tick 3 times before we stop it.

ECHO: "Tick at 0ms"
ECHO: "Tick at 500ms"
ECHO: "Tick at 1000ms"
ECHO: "Tick at 1500ms"
ECHO: "Ticker stopped"

Note that OpenSCAD doesn’t have built-in time management or concurrency features like channels or goroutines. This implementation simulates the behavior of a ticker using a loop and function calls. The timing is approximate and based on loop iterations rather than actual time.