STM32 dynamically change PWM compare value
The solution is to update the value synchronously instead of at random time. Perhaps in the overflow interrupt, if no other way is available. You don't say which STM32 you use, but some models have timers that have a preload feature which latch in the actual count from the register when counter starts a new cycle, you should fix your issue by enabling preload mode.