Update (a function) post’s featured image as soon as $image_url changes

Once you get URL of the image from Instagram and you know id of the post, you can use use the function from your question. You have to modify the code for the only if statement in it:

if( wp_mkdir_p( $upload_dir[ 'path' ] ) ) {
    $file = $upload_dir[ 'path' ] . "https://wordpress.stackexchange.com/" . $filename;
} else {
    $file = $upload_dir[ 'basedir' ] . "https://wordpress.stackexchange.com/" . $filename;
}

This function will upload the image to the media library and set it as a featured image for your post. Tested!

Or, based on suggestion by @TomJNowell from his comment, use this code:

$attach_id = media_sideload_image( $image_url, $post_id, 'Instagram image', 'id' );
set_post_thumbnail( $post_id, $attach_id );