Timers in Bnlang

The built-in timers module schedules callbacks to fire from the event loop after a delay (in milliseconds), or repeatedly on an interval. There are only two functions to learn: timers.set and timers.interval.


timers.set — Fire Once After a Delay

timers.set(delay_ms, fn) schedules fn to run once, delay_ms milliseconds from now. Passing 0 defers the call until after the current synchronous code finishes — useful for breaking up work.

import "timers" as timers;

print("a");
timers.set(0,    function () { print("c — next tick"); });
timers.set(1000, function () { print("d — one second later"); });
print("b");

// Output:
// a
// b
// c — next tick
// d — one second later

timers.interval — Fire Repeatedly

timers.interval(delay_ms, fn) returns a cancel function. Call it to stop the interval.

import "timers" as timers;

var count  = 0;
var cancel = null;

function step() {
    count = count + 1;
    print("tick", count);
    if (count >= 3) {
        cancel();
        print("cancelled");
    }
}

cancel = timers.interval(1000, step);
print("scheduled");

What About setImmediate / process.nextTick?

Bnlang does not ship setImmediate or process.nextTick. Use timers.set(0, fn) for both use cases — the callback fires after the current tick finishes, in registration order.


Best Practices

  • Keep timer callbacks short — they share the event loop with every other in-flight request.
  • Always hold onto the cancel handle returned by interval so you can stop it; otherwise it will keep your program alive forever.
  • Don't poll with tight interval(1, ...) calls when an event-driven design would do — high-frequency intervals burn CPU.