Avoid random number cached in preprocess hook
First, try to pass a render element with a '#cache' value set, maybe like so:

$variables['imageSet'] = [
  '#type' =&gt; 'value',
  '#value' =&gt; $imageset,
  '#cache' =&gt; [
    'max-age' =&gt; 0,
  ],
];




Next, you could try to completely disable the cache for this node (though that's probably not the best idea).

$variables['#cache']['max-age'] = 0;




And last – but quite advanced – you can provide a custom controller, that returns an uncached JSON response with your calculations and then use a little JS script that fetches the JSON via Ajax and inserts it into some placeholder selector in your markup (for the placeholder you could even provide a pseudo field to be placed at a desired position via the admin UI).

I used exactly the concept described above to build User Online Status. You can simply grab a copy and check its code to get an idea how that works.