I have the following function, that is called once in my program. When there is no user interaction it starts over again and again by recursion when the array is printed out. But when a user clicks on a link the function shall be stopped first (no more output from the array) and then be started again with new parameters.
function getText(mode){
var para = mode;
var url = "getText.php?mode=" + para;
var arr = new Array();
//get array via ajax-request
var $div = $('#text_wrapper');
$.each(arr, function(index, value){
eachID = setTimeout(function(){
$div.html(value).stop(true, true).fadeIn().delay(5000).fadeOut();
if(index == (arr.length-1)){
clearTimeout(eachID);
getText(para);
}
}, 6000 * index);
});
}
My code doesn’t really stop the function but calling it once more. And that eventuates in multiple outputs and overlaying each other. How can I ensure that the function stops and runs just one at a time?
$(document).ready(function() {
$("#div1, #div2").click(function(e){
e.preventDefault();
var select = $(this).attr("id");
clearTimeout(eachID);
getText(select);
});
});
You keep overwriting
eachIDwith the latestsetTimeout, so when youclearTimeout(eachID)you are only stopping the last one.Personally, I like to do things like this:
This way, you only have one timer running, and you can clear it at any time.