Playing with Intervals

by Megan Rose

HTML

<button id="b1">Button 1</button>
<button id="b2">Button 2</button>
<button id="b3">Button 3</button>
<div id="display"></div>
<button id="start">Start Interval</button>
<button id="stop">Stop Interval</button>

CSS

p {
    margin-bottom: 10px;
}
#display {
    height: 50px;
    margin: 10px 0;
    background: #CCC;
    padding: 10px;
}
#start {
    background: green;
    color: white;
}
#stop {
    background: red;
    color: white;
}

JavaScript

var b1 = document.getElementById('b1'), b2 = document.getElementById('b2'), b3 = document.getElementById('b3');
var x = 0;
function showX() {
    // alert(x);
    jQuery("#display").html(x);
}
b1.onclick = function() {
    x = 0;
    showX();
    increment(x);
};
b2.onclick = function() {
    x = 1;
    showX();
    increment(x);
};
b3.onclick = function() {
    x = 2;
    showX();
    increment(x);
};

function increment() {
	x++;
    showX();
}

var start = document.getElementById('start');
start.onclick = function() {
	timer = setInterval(increment, 1000); // changed from 3000
};

var stop = document.getElementById('stop');
stop.onclick = function() {
	// Stop the setInterval if existing
    if (timer != false) {
        clearInterval(timer);
        timer = false;
    }
    jQuery("#display").append(' Stopped');
};

var timer;