Troubles with stimuli exhibition

Hello there. I am using psychtoolbox to run experiments. My stimuli were set to be exhibited with a maximum duration of 8s, but I needed to draw each stimulus in each frame as they are dynamic. Still, I finally got some considerable abnormal deviations over 8s, such as 8.6s, which means that there were some stimuli exhibited more than 8s. The number of this issue achieved 21 over 180 trials, I am very confused about why this happened and how this could be fixed? I calculated the number of frames I needed to draw using “8s/ifi”, and then drew the stimulus in a for loop.
I wrote the code on psychtoobox-3, and ran the code on MATLAB R2021b in a Windows 10 system. The hardware equipment info is as follows:
Monitor: XG2730 SERIES
GPU: Radeon RX Vega M GH Graphics
Monitor resolution: 1920 x 1080
Active signal resolution: 2560 x 1440
Refresh rate: 60Hz

This is the code for one trial:

StimuliTime = 8;
for fr = 1 : (StimuliTime/ifi)+1
    if fr == (StimuliTime/ifi) + 1
        test_Results{trial,5} = 'NA'; % keycode
        break
    end
    if   fr < (StimuliTime/ifi + 1)
        % Draw all of our dots to the screen in a single line of code
        % For help see: Screen DrawDots
        Screen('DrawDots', window, dotPositionMatrix_1,...
            dotSizes, dotColors, dotCenter, 2);
        vbl  = Screen('Flip', window, vbl + (waitframes - 0.5) * ifi);
    elseif  fr > (StimuliTime/ifi)
        Screen('FillRect', window, rectColor, centeredRect);
        vbl  = Screen('Flip', window, vbl + (waitframes - 0.5) * ifi);
    end
    if KbCheck
        [keyisdown, secs, keycode] = KbCheck;
        if keycode(EscKey)
            esc = 1; finishednum = finishednum; test_Results = test_Results;
            return
        elseif keycode(Leftkey) % in case other keycodes instead of preset ones
            vbl  = Screen('Flip', window, vbl + (waitframes - 0.5) * ifi);
            if strfind(KeyResponseMap{1,1},'left = happy') == 1
                test_Results{trial,5} = KbName(keycode); % keycode
            elseif strfind(KeyResponseMap{1,1},'left = angry') == 1
                test_Results{trial,5} = KbName(keycode); % keycode
            end
            dropcurrentloop = 1; % drop the loop
        elseif keycode(Rightkey)
            vbl  = Screen('Flip', window, vbl + (waitframes - 0.5) * ifi);
            if strfind(KeyResponseMap{1,1},'left = happy') == 1
                test_Results{trial,5} = KbName(keycode); %resp
            elseif strfind(KeyResponseMap{1,1},'left = angry') == 1
                test_Results{trial,5} = KbName(keycode); %resp
            end
            dropcurrentloop = 1; % drop the loop
        else
            continue
        end
        if dropcurrentloop == 1
            break
        end
    end
end