Joachim
Joachim

Reputation: 375

How can i stop pygame.time.set_timer?

I want to print the message 3 times. After then how can i stop pygame.time.set_timer in this example?

import pygame
 
pygame.init()
 
print_message = pygame.USEREVENT + 0

pygame.time.set_timer(print_message, 1000)

while True:
    for event in pygame.event.get():
        if event.type == print_message: 
            print("stop now ")`
  

Upvotes: 1

Views: 658

Answers (2)

floatingCatsAndDogs
floatingCatsAndDogs

Reputation: 53

this might not be the best solution but you can set the variable "print_message" to some thing else when you want it to stop

like this:

import pygame
 
pygame.init()
 
print_message = pygame.USEREVENT + 0

pygame.time.set_timer(print_message, 1000)

while True:
    for event in pygame.event.get():
        if event.type == print_message: 
            print("stop now ")
            print_message = 0

Upvotes: 1

Rabbid76
Rabbid76

Reputation: 211278

The timer event can be stopped by passing 0 to the time argument of pygame.time.set_timer:

import pygame
 
pygame.init()
 
print_message = pygame.USEREVENT + 0
pygame.time.set_timer(print_message, 1000)

while True:
    for event in pygame.event.get():
        if event.type == print_message: 
            pygame.time.set_timer(print_message, 0)

The pygame.time.set_timer also has an additional _loops_argument:

loops is an integer that denotes the number of events posted. If 0 (default) then the events will keep getting posted, unless explicitly stopped.

If you want to get just 1 singe event, call pygame.time.set_timer with argument 1:

import pygame
 
pygame.init()
 
print_message = pygame.USEREVENT + 0

pygame.time.set_timer(print_message, 1000, 1)  # <---

while True:
    for event in pygame.event.get():
        if event.type == print_message: 
            # [...]

Upvotes: 2

Related Questions