To avoid duplication of this code, you may want to consider wrapping the canvas.clearRect call with the new id creation in a separate function.