简体   繁体   中英

Weird behavior with SetTimeout

I'm trying to refresh a div with JavaScript every 20 seconds. This is my code:

$(document).ready(function(){
    refreshTable();
    updateTable();
});

function updateTable(){
    setTimeout( refreshTable, 20000);
    updateTable();
}

function refreshTable(){
    $('#table_list').load('table')
}

Once the page is ready, I can start my countdown. But this code is updating the table every 3 seconds. Can someone help me? What am I doing wrong?

Ps: I saw that is a common issue here, but any of the questions that I saw were able to help me.

You have infinite recursion:

function updateTable(){
    setTimeout( refreshTable, 20000);
    updateTable(); // Infinite recursion.
}

You should use setIinterval instead of making your setTimeout loop.

When the document is ready, you call updateTable .

After 20 seconds, it calls refreshTable but it immediately calls updateTable again. So it queues up another refreshTable and then hits updateTable again . This sticks it into an infinite loop … or at least into stack overflow.

You need to either:

  • Call updateTable from inside refreshTable instead of updateTable
  • Use setInterval in the ready handler instead of using setTimeout at all

As other answers are pointing out, you have infinite recursion in your updateTable function. You could instead use setInterval, which periodically runs the specified refreshTable function:

$(document).ready(function(){
  refreshTable();
  setInterval(refreshTable, 2000)
});

function refreshTable(){
  $('#table_list').load('table')
}
$(document).ready(function(){
    window.setInterval( function(){
        $('#table_list').load('table');
    }, 20000);
});

This might help you out, at least i hope so :D

I would recommend you to use the "complete" callback of the jQuery method ".load()"

$(document).ready(function(){
    refreshTable();
});

function refreshTable(){
    $('#table_list').load('table', function(){
        setTimeout( refreshTable, 20000);
    });
}

Thus, setTimeout will be executed after query processing and HTML insertion has been performed. Please notice that we don't need the "updateTable" auxiliary function anymore as we now call the "refreshTable" function recursively.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM