I want to change interval value of setInterval dynamically. I'm struggling due to presence of a loop in setInterval callback function. I have seen too many questions on stackoverflow. But there is no any solution which can help me. If anyone know answer then please explain with an example. Thank You. Here is my code.
<html>
<head>
<script type="text/javascript">
var speed = 10;
function updateSlider(slideAmount) {
speed = slideAmount;
}
function load() {
downloadUrl("points.xml", function (data) {
/* code */
abc();
});
function abc() {
function track() {
/* code */
downloadUrl("points.xml", function (data) {
var xml = data.responseXML;
var points = xml.documentElement.getElementsByTagName("point");
var i = 0;
setInterval(function () {
if (i != points.length) {
alert(speed);
}
i++;
}, 100 * speed);
});
}
track();
}
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest;
request.onreadystatechange = function () {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.setRequestHeader("Content-type", "text/xml");
request.send(null);
}
function doNothing() {
}
</script>
</head>
<body onload="load();">
<div id="slider">
5% <input id="slide" type="range" min="1" max="20" step="5" value="10" onchange="updateSlider(this.value)" /> 200%
</div>
<div id="chosen">10</div>
</body>
This is a version without setInterval i always use:
Usage:
The last parameter of the start function is a boolean if the function needs to be run at 0.
You can also find the script here: https://github.com/Atticweb/smart-interval
The trick is to not use
setInterval
, and to usesetTimeout
in a loop instead.setInterval
reads the timing value you give it once, schedules based on this timing, and forgets about it. The only thing you can do isclearInterval(myInterval)
if you've assigned your interval to a variable likemyInterval
.setTimeout
is much the same, except we can use it to manually loop on the same function. Manually looping allows us to change the timing ofsetTimeout
after each timeout.Here's a quick example. Moving the slider to the left makes the ticking faster, and to the right, slower.
DEMO
As a side note: Using this pattern is almost always a better option than using
setInterval
.setInterval
runs the chance that your function execution could take longer than the duration of the interval. This never happens with a loopingsetTimeout
if you callsetTimeout
last in the function.Documentation: