Skip to content

Instantly share code, notes, and snippets.

@santosh
Created October 14, 2018 05:50
Show Gist options
  • Save santosh/568dfc463d8c3f341741b34355db2129 to your computer and use it in GitHub Desktop.
Save santosh/568dfc463d8c3f341741b34355db2129 to your computer and use it in GitHub Desktop.
Working with setInterval and setTimeout in #JavaScript
body {
background: #eee;
}
#message {
width: 400px;
background: #ddaaaa;
padding: 20px;
font-family: "Gill Sans", "Gill Sans MT", Calibri, "Trebuchet MS", sans-serif;
font-size: 18px;
color: #444;
margin: 0 auto;
text-align: center;
border: 1px solid #ff7777;
font-weight: bold;
opacity: 0;
-webkit-transition: opacity 0.7s;
-moz-transition: opacity 0.7s;
transition: opacity 0.7s;
}
#message.show {
opacity: 1;
-webkit-transition: opacity 0.7s;
-moz-transition: opacity 0.7s;
transition: opacity 0.7s;
}
#colour-changer {
width: 200px;
height: 100px;
margin: 30px auto;
border: 1px solid #000;
background: #fff;
-webkit-transition: background 0.7s;
-moz-transition: background 0.7s;
transition: background 0.7s;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>JavaScript</title>
<link rel="stylesheet" href="timers.css" type="text/css" media="screen" charset="utf-8">
</head>
<body>
<div id="message">
<p>This is really important notification.</p>
<p>The description of the message.</p>
</div>
<div id="colour-changer">
</div>
<script src="timers.js"></script>
</body>
</html>
var myMessage = document.getElementById("message");
var colourChanger = document.getElementById("colour-changer");
var colours = ["red", "blue", "green", "pink"];
var counter = 0;
function showMessage() {
myMessage.className = "show";
}
setTimeout(showMessage, 3000);
function changeColour() {
if (counter >= colours.length) {
counter = 0;
}
colourChanger.style.background = colours[counter];
counter++;
}
var colourTimer = setInterval(changeColour, 2000);
colourChanger.onclick = function() {
// this is how we reset an interval
clearInterval(colourTimer);
colourChanger.innerHTML = "Timer Stopped";
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment