0

i have a countdown timer when it finish it run a php script (file called ajax.php) the problem is the ajax.php run many times .

i want to get this result in the table

[id][content]
[1][timer]

but i get this result

[id][content]
[1][timer]
[2][timer]
[3][timer]
[4][timer]
[5][timer]
[6][timer]
[7][timer]
[8][timer]
[9][timer]
.....

this is the code

    <div id="counter"></div>

    <script src="jquery.js"></script>
    <script>
    var div = $('#counter');

    var n = 5000;

    var blured = false;

    var tid = setInterval(function() {
        if (blured) return;    
        n -= 100;
        div.text( (n / 1000).toFixed(1) + ' seconds passed' );
        if ( n <= 0 ) {


        div.text('Time passed!'); 
        $.ajax({

        url: 'ajax.php',
        type: 'post',
        success: function(data, status) {}

        });




        }


    }, 100);

    window.onblur = function() {
        blured = true;    
    };

    window.onfocus = function() {
        blured = false;    
    };


        document.getElementById("progress").innerHTML="<div style=\"width:'.$percent.';background-color:#ddd;\">&nbsp;</div>";
        // document.getElementById("information").innerHTML="'.$i.' row(s) processed.";
        window.onblur = function() {
            blured = true;    
        };
        window.onfocus = function() {
            blured = false;    
        };


    </script>

and this is ajax.php

    mysql_connect("localhost","root","usbw") or die ("Couldn't connect to server");
    mysql_select_db("test") or die ("Coouldn't Select Database");


    $query = mysql_query("INSERT INTO add_delete_record VALUES ('', 'timer')");

2 Answers 2

1

This is actually how setInterval works. From your code I can see that you are setting it to 100 milliseconds, therefore your browser will make the ajax call once every 0.1 second and it will go on forever. In order to avoid it you must first know that the function setInterval() returns an ID that you can use to later clear that event handler. Simply use clearInterval().

Example:

var tid = setInterval(function(){},100);

/*Later you can use*/
clearInterval(tid);

If you need more information checkout the documentation for setInterval() and clearInterval().

Sign up to request clarification or add additional context in comments.

Comments

0
    var tid = setInterval(function() {
    if (blured) return;    
    n -= 100;
    div.text( (n / 1000).toFixed(1) + ' seconds passed' );
    if ( n <= 0 ) {


    div.text('Time passed!'); 
  clearTimeout(tid);
    $.ajax({

    url: 'ajax.php',
    type: 'post',
    success: function(data, status) {}

    });




    }


}, 100);

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.