Timers not affected by Time Dilation

You can do it in C++ by calling an AsyncTask that creates a sleeping thread for the amount of seconds specified, and that calls a delegate. Not the best way but it works for most case and you can be sure Time Dilation or Pause won’t interfere.

void SetAbsoluteTimer(FTimerDelegate Delegate, float Delay,
	bool bLooping)
{
	float UsedDelay = Delay;
	AsyncTask(ENamedThreads::AnyBackgroundThreadNormalTask, [&, Delegate, UsedDelay, bLooping]()
   {
	   while (true)
	   {
		   FPlatformProcess::Sleep(UsedDelay);

		   AsyncTask(ENamedThreads::GameThread, [&, Delegate]()
		   {
			   Delegate.ExecuteIfBound();
		   });

		   if (!bLooping)
		   	break;
	   }
   });
}

void SetAbsoluteTimer(TFunction<void()>&& Callback, float Delay, bool bLooping)
{
	SetAbsoluteTimer(FTimerDelegate::CreateLambda(Callback), Delay, bLooping);
}

You can then use it like any Timer

SetAbsoluteTimer([&]
{
	// Do Stuff ...
			
}, 1.0f, false);

EDIT : It can cause a crash if the game is stopped or the current level is changed during a timer. I haven’t dug into it yet.

2 Likes