Skip to content

Instantly share code, notes, and snippets.

@brenopolanski
Created November 21, 2015 23:45
Show Gist options
  • Save brenopolanski/f326b53954769664f21f to your computer and use it in GitHub Desktop.
Save brenopolanski/f326b53954769664f21f to your computer and use it in GitHub Desktop.
Start, Stop and Reset Javascript SetInterval
<div class="btns">
<a href="" id="set" class="btn">Set/Reset</a>
<a href="" id="stop" class="btn">Stop</a>
</div>
<div id="container"></div>
var timer = 0;
function setResetInterval(bool){
var el = $("#container");
if(bool){
timer = setInterval(function(){
el.css("background", "red");
setTimeout(function(){
el.css("background", "blue");
},500);
},1000);
}else{
clearInterval(timer);
}
}
$("#set").click(function(e){
e.preventDefault();
setResetInterval(true);
});
$("#stop").click(function(e){
e.preventDefault();
setResetInterval(false);
});
#container{
background: blue;
width: 50px;
height: 50px;
}
.btn{
text-decoration:none;
background: grey;
color: #fff;
padding: 5px;
margin: 5px;
margin-bottom: 10px;
}
.btns{
height: 50px;
display:block;
padding: 3px;
}
@tepetar
Copy link

tepetar commented Jun 2, 2019

Code in ZIP file is not working ! Is it true or I @am doing something wrong ? Except two text marks "Set/Reset" and "Stop" I can not get anything else - no buttons, no container... What version of jQuery need I to use ?

@am
Copy link

am commented Jun 3, 2019

@tepetar mentioning me is what you did wrong, either way, it should work, here is a working sandbox of this same code: https://codesandbox.io/embed/sharp-hodgkin-jinir?fontsize=14

EDIT: Don't download the zip file, I see your problem now. The html here is just an example, it does not import the script or the styles...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment