Creating a custom wordpress widget and stopping js from running twice(once in active widget once in widget selector)?

Use wp_enqueue_script. You assign a name to your js file when enqueued, and it will stop a file from being enqueued multiple times.
Right now your JS is simple enough, but as it gets more complex, it’s better to have it outside in it’s on .js file.

add_action( 'wp_enqueue_scripts', 'add_my_js' );
function add_my_js() {
    wp_enqueue_script( 'my-script', get_stylesheet_directory_uri() . '/js/my-script.js' );
}

To add variables to your JS files, look at wp_localize_script. this allows you to point to the same JS handle (in this case, my-script, and attach variables onto them through a single object. Example:

 add_action( 'wp_enqueue_scripts', 'add_my_js' );
    function add_my_js() {
        wp_enqueue_script( 'my-script', get_stylesheet_directory_uri() . '/js/my-script.js' );
       wp_localize_script( 'my-script', 'myData', array( 'var1' => $variable1, 'var2' => $something_else ) );
    }

Then, within your JS file, you can call upon myData.var1 and myData.var2 in Object notation.

One thing to keep in mind here is those variables need to already be set by the time the wp_enqueue_scripts action is called, so best do the declarations before then, or within your function if not already set.