UI Timers in AL, without Javascript

The normal way to add a timer to a page in AL is through JavaScript. I did a video on that 6 years ago, all the way back on version 16. Since then, a new way to create a timer has emerged: Using PageBackgroundTasks. Check out the video for the nerdy details.

https://youtu.be/5EF48ZgY4Ms

In this video, Erik demonstrates how to create a UI timer on a Business Central page using AL’s built-in page background tasks — no JavaScript required. He walks through the full implementation, explains the key gotchas around primary keys and page lifecycle, and shows how to pass parameters to and from the background task code unit.

Background: The JavaScript Approach

Way back in some of Erik’s earliest videos (including the famous Tic-Tac-Toe game), he showed how to create a timer on a Business Central page by embedding a tiny one-pixel JavaScript user control add-in. The JavaScript timer would fire events back to AL at regular intervals — for example, simulating the computer “thinking” before making a move.

But someone recently reminded Erik that there’s another way to achieve the same effect using a purely AL-based approach: page background tasks.

Setting Up the Page Background Task Timer

The idea is simple: use CurrPage.EnqueueBackgroundTask to kick off a background code unit that sleeps for a specified duration, then handle the completion event to perform your timer logic and re-enqueue the task.

The Background Code Unit

First, you need a code unit that will serve as your timer. Initially, it can be as simple as a sleep call:

codeunit 50100 Timer
{
    TableNo = Integer;

    trigger OnRun()
    var
        Parm: Dictionary of [Text, Text];
        Seconds: Integer;
    begin
        Parm := Page.GetBackgroundParameters();
        Evaluate(Seconds, Parm.Get('seconds'));
        Sleep(Seconds * 1000);

        Result.Add('slept', Format(Seconds * 1000));
        Page.SetBackgroundTaskResult(Result);
    end;

    var
        Result: Dictionary of [Text, Text];
}

A few important things to note about this code unit:

  • It runs in read-only mode — you cannot write to the database from a page background task. You’re outside of transactional scope.
  • You retrieve input parameters using Page.GetBackgroundParameters(), which returns a Dictionary of [Text, Text].
  • You send results back using Page.SetBackgroundTaskResult(), also a Dictionary of [Text, Text].

The Page Implementation

On the page side, you enqueue the background task and handle its completion. Here’s the key structure:

page 50100 "My Timer Page"
{
    PageType = Card;
    SourceTable = "Some Table";

    layout
    {
        area(Content)
        {
            field(Counter; Counter)
            {
                Editable = false;
            }
        }
    }

    actions
    {
        area(Processing)
        {
            action(Ping)
            {
                Caption = 'Ping';

                trigger OnAction()
                begin
                    StartTimer();
                end;
            }
        }
    }

    trigger OnPageBackgroundTaskCompleted(TaskId: Integer; Results: Dictionary of [Text, Text])
    begin
        if TaskId = GlobalTaskId then begin
            Counter += 1;
            StartTimer();
        end;
    end;

    trigger OnPageBackgroundTaskError(TaskId: Integer; ErrorCode: Text; ErrorText: Text; ErrorCallStack: Text; var IsHandled: Boolean)
    begin
        // Handle errors if needed
    end;

    local procedure StartTimer()
    var
        Parm: Dictionary of [Text, Text];
    begin
        Parm.Add('seconds', '2');
        CurrPage.EnqueueBackgroundTask(GlobalTaskId, Codeunit::Timer, Parm, 60000, PageBackgroundTaskErrorLevel::Error);
    end;

    var
        GlobalTaskId: Integer;
        Counter: Integer;
}

The EnqueueBackgroundTask function takes these parameters:

  1. Task ID — an integer variable where the system stores the ID of the enqueued task. You need this to identify which task completed in the callback.
  2. Codeunit ID — the code unit to run in the background.
  3. Parameters — a Dictionary of [Text, Text] to pass data to the background task.
  4. Timeout — a failsafe in milliseconds (e.g., 60000 for one minute).
  5. Error Level — determines how errors in the background task surface on the page.

Creating a Repeating Timer

To make the timer repeat, simply re-enqueue the background task inside the OnPageBackgroundTaskCompleted trigger. Each time the task completes, you do your work (increment the counter, refresh data, etc.) and then call StartTimer() again. This creates a continuous loop — the timer fires, completes, re-enqueues, and fires again.

The Big Gotcha: Primary Keys

This is the most important thing to understand about this approach. Erik highlights a diagram from Microsoft’s documentation that illustrates the issue:

When you call EnqueueBackgroundTask, the task is tagged with the current primary key of the page’s source record. When the task completes and tries to call back to the page, Business Central checks whether the primary key is still the same. If it has changed — for example, because the user navigated to a different record on a list page — the task is silently canceled.

  • You won’t get an error trigger.
  • You won’t get any programmatic indication that the task was canceled.
  • It just disappears.

This means:

  • Card pages where the primary key doesn’t change — this approach works great.
  • List pages where clicking around changes the selected record — this will not work reliably, and you’re better off using the JavaScript approach.

Another Gotcha: OnOpenPage Timing

Erik demonstrates another subtle issue. If you try to enqueue the background task in the OnOpenPage trigger, it may not work because at that point, the page may not yet have a primary key selected. The record is loaded after OnOpenPage completes.

One workaround Erik shows is to force a record retrieval before enqueuing:

trigger OnOpenPage()
var
    Rec: Record "Some Table";
begin
    Rec.FindFirst(); // Force a record to be selected
    StartTimer();
end;

But this is a bit of a hack — it’s important to be aware of the page lifecycle and when the source record is actually available.

JavaScript vs. Background Task Timers

Erik summarizes the trade-offs between the two approaches:

Aspect Background Task Timer JavaScript Timer
Requires JavaScript add-in No Yes
Works on list pages Unreliable (primary key changes) Yes
Works on card pages Yes Yes
Independence from page state Tied to primary key Independent
Callback reliability Reliable (server-side) Not 100% guaranteed (browser may be busy)

Conclusion

Page background tasks give you a clean, JavaScript-free way to implement timers in Business Central’s UI. The technique is straightforward: enqueue a background task that sleeps for your desired interval, handle the completion event, do your work, and re-enqueue. Just be mindful of the primary key gotcha — this approach is best suited for card pages or scenarios where the source record doesn’t change. For list pages or situations requiring more reliability regardless of page state, the JavaScript control add-in approach remains the better choice. Either way, it’s another useful tool in your AL developer toolbox.