2

im having a problem, I cant seem to stop the timer... in fact it speeds up!

var number = 0;
var timer;
function get_data( url ){
    number++;
    $('#requests').html( number );
    $.ajax({ 
        type: 'POST', url: './includes/ajaxGetData.php', data: 'url=' + encodeURIComponent(url), cache: false, timeout: 10000,
        error : function(){ 
            timer = window.setTimeout( get_data( url ), 2000 );
        },
        success: function(html){ 
            if( html.substr(0,12) == '<!-- die -->' ) {
                $("#result").html('<p>Complete...</p>' + html );
                $('#requests').html('');
                clearTimeout(timer);
            }else{
                $("#result").html(html);
                timer = window.setTimeout( get_data( url ), 2000 );
            }
        }                           
    });
}
get_data( 'http://example.com' );

can anyone see where im going wrong?

2 Answers 2

2
timer = window.setTimeout( get_data( url ), 2000 );

This calls get_data and creates a timeout for the result of this call. Use something along these lines:

timer = window.setTimeout(function () { get_data(url) }, 2000);
Sign up to request clarification or add additional context in comments.

1 Comment

i did think this and had your second line of code originally with no luck.
0

The speeding up comes from the setTimeout in the if else in your succes, which seems to be always else.

Try this for html comment selection

$(html).match(/<!--.*?-->/g));

or in your case

$(html).match(/<!-- die -->/g));

And think about what happens if you overwrite an already set Timer

timer = window.setTimeout( get_data( url ), 2000 );

clear it befor you set a new one, otherwise "the old" will fire

clearTimeout(timer);
timer = window.setTimeout( get_data( url ), 2000 );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.