Please, don't pass a string to setInterval
, JS functions are first-class objects, so they can be passed as arguments, assigned to variables or returned by other functions. In your example, I'd write the following:
<input type="button" value="Start" id="intervalStart"/>
<input type="button" value="Start" id="intervalStop"/>
And then, the JS:
window.onload = function()//not the best way, but just as an example
{
var timer, num = 0,
numDiv = document.getElementById('num_div');//<-- only scan dom once, not on every function call
document.getElementById('intervalStart').onclick = function(e)
{
this.setAttribute('disabled','disabled');//disable start btn, so it can't be clicked multiple times
timer = setInterval(function()
{
numDiv.innerHTML = ++num;
},1000);
};
document.getElementById('intervalStop').onclick = function(e)
{
document.getElementById('intervalStart').removeAttribute('disabled');//enable start again, you could do the same with disable btn, too
clearInterval(timer);
num = 0;
numDiv.innerHTML = '';
};
};
This code needs some more work, though at least it doesn't pollute the global namespace too much.
Do note that I've used a variable to reference the num_div
element, that way your interval callback function doesn't have to scan the entire DOM for that element every 1000ms. It's not much, but keep in mind that every time you use a jQuery selector, or a getElement(s)By*
method, JS has to traverse the DOM and look for the element. Keeping a reference to an element you'll be needing a lot just makes for a more efficient script.