black_yurizan black_yurizan - 3 months ago 11
HTML Question

I cannot run setInterval and another function at the same time

I have two functions that are supposed to run when I click on a button. The first function is a setInterval function that increments the variable num by 0.01 and displays it in a div id called result. The second function generates an object literal into a json string and displays it in a div id called output. When I click on the button, only the JSON string is outputted, but it seems as though the setInterval doesn't run and I don't know why. Here is the link for example

HTML

<button>
click
</button>
<div id="result">

</div>
<div id="output">

</div>


Javascript

var timer,
result = document.getElementById("result"),
num,
link ={
name:"link",
weapon:"master sword",
mute:true,
race:"hyrulian",
age:16
};

/* ---------- GENERATE JSON OBJECT --*/
function generate(){
var data = {};
for(var prop in link){
data[prop] = link[prop];
}
data = JSON.stringify(data);
document.getElementById("output").innerHTML = data;
}

/* ---------- CLICK BUTTON --*/
document.querySelector("button").onclick = function(){

num = 0;
function callBack(){
num += 0.01;
result.innerHTML = num.toFixed(2);

}
timer = setInterval(callBack,10);
generate();
clearInterval(timer);

}

Answer

Updated My Answer: You have to wrap your callBack(); function in the setInterval with an anonymous function. This is because setInterval expects a reference to a Function that should be executed every few milliseconds (the interval you specify). You should use it like this setInterval( function(){ callBack(); }, 10);. This should give you the desired result.

Same code, I just updated the setInterval( function(){ callBack(); }, 10); line:

var timer,
    result = document.getElementById("result"),
num,
link ={
 name:"link",
 weapon:"master sword",
 mute:true,
 race:"hyrulian",
 age:16
};

/* ---------- GENERATE JSON OBJECT --*/
function generate(){
var data = {};
for(var prop in link){
   data[prop] = link[prop];
}
data = JSON.stringify(data);
document.getElementById("output").innerHTML = data;
}

/* ---------- CLICK BUTTON --*/
document.querySelector("button").onclick = function(){

num = 0;
  function callBack(){
 num += 0.01;
 result.innerHTML = num.toFixed(2);

 }
 timer = setInterval( function(){ callBack(); },10); // I modified this line
 // timer = setInterval(callBack,10);
 generate();
 clearInterval(timer);
 // setTimeout( function(){ clearInterval(timer); }, 1000); // This can be used to test that the timer has indeed started, you can wait 1 second before you clear the timer

 }
Comments