jesloudr jesloudr - 3 months ago 9
Ajax Question

How to stop ajax timer if results contains key

I have a simple ajax function:

<script type="text/javascript"
src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
function crunchifyAjax() {
$.ajax({
url: '/user/show-user-task-messages?code=<c:out value="${liveCode}"/>',
success: function (data) {
$('#result').html(data);
}
});
}
</script>
<script type="text/javascript">
var intervalId = 0;
intervalId = setInterval(crunchifyAjax, 100);
</script>


The function check every 100ms my url and return some text like this:

10
9
8
7
6
5
4
3
2
1
stop


I want to break this timer after
data
contains stop. How can I do this?

Any help in this regard is much appreciated.

Answer

Try this:

<script type="text/javascript"
src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
    function crunchifyAjax() {
        $.ajax({
            url: '/user/show-user-task-messages?code=<c:out value="${liveCode}"/>',
            success: function (data) {
                $('#result').html(data);
                if((""+data).indexOf("stop") > -1)
                    clearInterval(intervalId); //clearing the interval started by setInterval
            }
        });
    }
</script>
<script type="text/javascript">
    var intervalId = 0;
    intervalId = setInterval(crunchifyAjax, 100);
</script>