Implementing an Application Loop

How to Use SDL Timers in Game Development

Can you explain how to use SDL timers to trigger events at regular intervals?

Abstract art representing computer programming

SDL timers are a useful tool to perform actions at set intervals, independent of your main game loop. Here’s a simple way to set up a timer that triggers every second:

#include <SDL.h>
#include <iostream>

Uint32 my_callback(Uint32 interval, void* param) {
  std::cout << "Timer callback triggered!\n";
  // Return the interval to reset the timer
  return interval;
}

int main(int argc, char** argv) {
  SDL_Init(SDL_INIT_TIMER);
  SDL_TimerID my_timer_id = SDL_AddTimer(
    1000, my_callback, NULL);

  bool running = true;
  SDL_Event event;
  while (running) {
    while (SDL_PollEvent(&event)) {
      if (event.type == SDL_QUIT) running = false;
    }
  }

  SDL_RemoveTimer(my_timer_id);
  SDL_Quit();
  return 0;
}
Timer callback triggered!
Timer callback triggered!
Timer callback triggered!

This timer will call my_callback() every 1000 milliseconds (1 second), and it will print a message to the console each time it is triggered.

Answers to questions are automatically generated and may not have been reviewed.

3D art representing computer programming
Part of the course:

Building Minesweeper with C++ and SDL2

Apply what we learned to build an interactive, portfolio-ready capstone project using C++ and the SDL2 library

Free, unlimited access

This course includes:

  • 37 Lessons
  • 100+ Code Samples
  • 92% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved