Skip to content

Instantly share code, notes, and snippets.

@tinshade
Created August 13, 2021 07:32
Show Gist options
  • Save tinshade/37852dcd72a426e1e4692d679aca7c91 to your computer and use it in GitHub Desktop.
Save tinshade/37852dcd72a426e1e4692d679aca7c91 to your computer and use it in GitHub Desktop.
Clearing a setInterval on a HTML page with vanilla JS
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Clear Interval Test</title>
</head>
<body>
<h1>Clear setInterval w/ JS</h1>
<br/>
<h4 id="status">Click Start</h4>
<br/>
<button onclick="startInterval()">Start</button>
<button onclick="stopInterval()">Stop</button>
<br/>
<small id="count">0</small>
<script>
let counter = null;
const count = document.getElementById('count');
const status = document.getElementById('status');
function startInterval(){
status.innerHTML = "Interval Function Started";
counter = setInterval(()=>{
count.innerHTML = parseInt(count.innerHTML)+1;
}, 500);
}
function stopInterval(){
status.innerHTML = "Interval Function Stopped";
clearInterval(counter);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment