See here: how many javascript setTimeout/ setInterval call can be set simultaneously in one page?
Basically, you need to assign the result of setInterval to a variable. Doing so will allow you to then use clearInterval with that variable
I've used that technique in this example. Doing it this way allows you to change the interval assigned to different elements - we first check to see if we have any saved values. If so, we call clearTimeout on them.
From there, we call setInterval on each target item, saving the result to the array - ready to be cleared next time the user presses the button.
<!DOCTYPE html>
<html>
<head>
<title>Moving a couple of spans with different intervals</title>
<script type="text/javascript">
var myIntervals = [];
function Init()
{
if (myIntervals.length != 0)
{
for (var i=0, n=myIntervals.length; i<n; i++)
{
clearInterval(myIntervals.pop());
}
}
myIntervals.push(setInterval(function(){onMove('sp1');}, (Math.random()*500)>>0 ));
myIntervals.push(setInterval(function(){onMove('sp2');}, (Math.random()*500)>>0 ));
myIntervals.push(setInterval(function(){onMove('sp3');}, (Math.random()*500)>>0 ));
}
function constructStyleString(xPos, yPos)
{
var result = "margin-top: " + yPos + "px;";
result += "margin-left: " + xPos + "px;";
return result;
}
function onMove(tgtId)
{
var xPos, yPos;
xPos = Math.random() * 640;
yPos = Math.random() * 480;
var elem = document.getElementById(tgtId);
elem.setAttribute("style", constructStyleString(xPos, yPos));
}
</script>
<style>
span
{
position: absolute;
}
</style>
</head>
<body onload="Init();">
<button onclick="Init();">(Re)set item intervals</button>
<span id='sp1'>This is the first item</span>
<span id='sp2'>This is the second item</span>
<span id='sp3'>This is the third item</span>
</body>
</html>