Efficient Code to run a servo with

Hello, im a beginner in arduino and currently I am doing a project that uses:

Ultrasonic sensor 1x
Mg90 servo 1x

During my tests, i noticed that my servo would often "twitch" or not continuously turn to its angle limit and I've speculated that it might be the current being drawn out by the components which lead me here. When I was looking up various topics that may helped me, One topic came across that particularly specified the use of millis() function and that it may help my board to smoothen out the supposed "delays" i used in my code as it did not completely halted the procedure in the section of my servo's control code. Going back to the topic, Im here to ask if there are more "efficient" ways to program various and different components that I am most definitely not aware of. thanks for reading!

Welcome to the forum

How is the servo powered ?

Please post your sketch, using code tags when you do, and a schematic of your project. A photo of a hand drawn circuit is good enough as long as it shows how the components are connected and powered and the type of Arduino board that you are using

hello, this is the code and that i used(without ultrasonic part yet), ive also tried recreating the wiring of what i did on a simulater

#include <Servo.h>
Servo myServo;
unsigned long previousMillis = 0;  
const long interval = 5;  
int position = 0;         
bool increasing = true;   

void setup() {
    myServo.attach(2); 
}

void loop() {
    unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis; 

    myServo.write(position);

        
 if (increasing) {
   position++; 
    if (position >= 180) {
      increasing = false; 
    }
  } else {
    position--; 
  if (position <= 0) {
    increasing = true;
    }
   }
 }
}

this is the previous code which is what the millis() one is based off:

  for (int i = 0; i <= 180; i++) {
    myServo.write(i);
    delay(4.5); 
    }
  
  for (int i = 180; i >= 0; i--) {
    myServo.write(i);
    delay(4.5); 
    }