Cursos still staying on screen even though it shouldn't be visible

Alright so, I’ve read through lots of threads like these but none of them address my problem.

I have a javascript code, and when you press tab or esc, the mouse becomes visible and unlocked, however when you exit the tab/esc menus, it doesn’t make it invisible. Heres my code:

var BlackScreen : GameObject;
var FadeScreen : GameObject;

function Start() {
   yield WaitForSeconds(1);
   Cursor.lockState = CursorLockMode.None;
   FadeScreen.GetComponent("Animator").enabled=true;
   BlackScreen.SetActive(false);
   yield WaitForSeconds(1.99);
   FadeScreen.GetComponent("Animator").enabled=false;
   FadeScreen.SetActive(false);
}

function Update() {
if (Input.GetKeyDown (KeyCode.Tab) || (KeyCode.escape)) {
   Cursor.lockState = CursorLockMode.None;
   Cursor.visible = true;
   Cursor.lockState = CursorLockMode.Confined;

} else if (Cursor.lockState != CursorLockMode.Confined) {
   Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}}

I have a feeling it may have to do with the fact that you press the tab/esc key a second time to leave their relative menus, meaning it makes it visible again.

Any suggestions and an explanation of what you’d do would be much appreciated.

Change the Update function to this

function Update()
{
    if (Input.GetKeyDown (KeyCode.Tab) || Input.GetKeyDown (KeyCode.escape))
    {
        if (Cursor.visible)
        {
            Cursor.visible = false;
            Cursor.lockState = CursorLockMode.Locked;
        }
        else
        {
            Cursor.lockState = CursorLockMode.None;
            Cursor.visible = true;
            Cursor.lockState = CursorLockMode.Confined;
        }
    }
}

or this. They both do the same thing.

function Update()
{
    if (Input.GetKeyDown (KeyCode.Tab) || Input.GetKeyDown (KeyCode.escape))
    {
        if (Cursor.visible)
        {
            Cursor.lockState = CursorLockMode.Locked;
        }
        else
        {
            Cursor.lockState = CursorLockMode.None;
            Cursor.lockState = CursorLockMode.Confined;
        }
        Cursor.visible = !Cursor.visible;
    }
}