Onload gets triggered when refreshing the site. You‘d have to save the state outside the scope of the function. If you‘re using a statis webpage and you simply added the script to the head, then the script always gets executed on page load. Look into webservers. Node.js with express library for example.