player.stopVideo, player.playVideo, etc. not working outside of event functions calls with youtube-api

I am trying to create a button that allows the user to click it and stop the embedded youtube video. However, whenever I try and call the player object itself to use the function player.playVideo() I get an error saying the function is not defined.

Player is globally defined and set when the Youtube API loads (just like the tutorial on their website). Function calls to playVideo work just fine when events trigger their usage, but using it outside of those simply do not work.

'''javascript // 2. This code loads the IFrame Player API code asynchronously. var tag = document.createElement('script');  tag.src = ""; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);  // 3. This function creates an <iframe> (and YouTube player) //    after the API code downloads. var player; function onYouTubeIframeAPIReady() {     isReady=true;     player = new YT.Player('player', {         height: '390',         width: '640',         videoId: 'M7lc1UVf-VE',         events: {             'onReady': onPlayerReady,             'onStateChange': onPlayerStateChange         }     }); }  // 4. The API will call this function when the video player is ready. function onPlayerReady(event) {     playVideo(); }  // 5. The API calls this function when the player's state changes. //    The function indicates that when playing a video (state=1), //    the player should play for six seconds and then stop. var done = false; function onPlayerStateChange(event) {     if ( == YT.PlayerState.PLAYING && !done) {         setTimeout(stopVideo, 6000);         done = true;     } } function stopVideo() {     player.pauseVideo(); }  function playVideo() {     player.playVideo(); }  //The function that is run when the button is pressed, only in this case                        // stopVideo not work! function togglePlay() {     if(isPlaying) {         stopVideo();     } else {         playVideo();     } } ''' 

Expected: Youtube video plays Actual: Error player.playVideo is not a function