One method to acheive stable timing and complete synchronization with another signal is simply to poll the signal and take counter measures. The signal in this case could be the raster beam (stable rasters) or f.e. the drive CPU.
Let's examplify with with polling the raster beam. We know $d012 contains lower 8 bits (out of nine) of the current raster line counter, and will increase by one every 63rd cycle.
Consider the following code:
lda #$30 cmp $d012 bne *-3
Since each loop here takes 5 cycles we'll have a jitter of up to 5 cycles. I.e. after the bne the beam will be on cycle 2-7. Imagine pushing this jitter so that it crosses the boundary between raster line #$30 and #$31 now by applying some NOPs (58cycles). If we add 58 cycles to the 2-7 jitter we get a jitter on 60-65 or in terms of raster lines 60-62(line #$30) and 0-2(line #$31). Within this intervall we want to poll $d012 again so by adding a lda $d012 and compensate that read in the 58cycles delay by 4 cycles we now will have a value that sometimes is #$30 (too early) or sometimes is #$31.
ldx #$30 lp1: cpx $d012 bne lp1 jsr cycles bit $ea nop cpx $d012 beq skip1 nop nop skip1: jsr cycles bit $ea nop cpx $d012 beq skip2 bit $ea skip2: jsr cycles nop nop nop cpx $d012 bne onecycle onecycle: rts cycles: ldy #$06 lp2: dey bne lp2 inx nop nop rts
To be continued…