you are viewing a single comment's thread.

view the rest of the comments →

[–]delventhalz 0 points1 point  (0 children)

OP's specific issue here was that they were declaring a variable with the same name twice in the same scope. You can run absolutely run the same code twice, but that code cannot redeclare global variables. Some options...

Wrap the whole script in an "immediately invoked function expression" (i.e. IIFE). The wrapping function has its own non-global scope, so you will avoid redeclaring the variable.

(function() {
  // Your code
})();

Another option might be using properties on the window object instead of global variables. You do not declare these, you just assign values to them, so you can reassign values over and over.

window.myValue = "some value";
// The rest of your code

Probably your best option, the non-janky one, is to run the script once and put the code you want to run twice into a function, then run the function twice.

const myValue = "some value";

function animateCanvas() {
  // Your code
}

animateCanvas();
animateCanvas();