Requirement is pretty simple, for some reasons I am unable to sort this out. Outer function calls inner function. Inner function is asynchronous, calls inner function on success if condition is matched. All fine - now user can run outer function while inner function is in progress. I want inner function to stop working immediately, and start afresh.
document.getElementById("demo").addEventListener("click", function() {
demo_click();
});
//
function demo_click() {
var idnum = 0;
var length = 25;
innerFunc();
//
function innerFunc() {
if (idnum < length) {
console.log(idnum);
setTimeout(function() {
idnum++;
innerFunc();
}, 500);
}
}
}
It logs from 0 to 24 as expected. Here is fiddle - https://jsfiddle.net/h7ab8u69/2/
Solution might be trivial, but please suggest me what / where to put the condition.
EDIT
From start afresh I meant that previous calls of innerFunc would stop and it will start logging (console) from zero. It still starts from zero, but if you click twice, thrice and so on - logs (console) will appear from previous calls of innerFunc as well. Please visit above fiddle link and open console and click on button - problem will be evident.
PS
SetTimeout is just to display asynchronous call. In my code, which is Image.onLoad event. So, clearing the timeout is not an option. Basically, I am loading image one after another on button click. I want to stop previous loading and start new loading on another click. To make it simple, I used SetTimeout.
//var imgArray = [‘0.jpg’, ‘1.jpg’, ‘2.jpg’ and so on]
function innerFunc() {
var img = new Image;
img.onload = function() {
//draw this image on canvas
//code to draw
// draw next only if some condition is correct
if (idnum < length) {
idnum++;
innerFunc();
}
};
img.src = imgArray[idnum];
}