How can I prevent my recursive function from crashing the browser in JavaScript