简体   繁体   中英

Ajax Load is working recursive in setTimeout?

I have used the ajax load function inside the setTimeout while page loading,the ajax load function will be called after the particular time,

The thing is that its been working after the setTimeout completed. Its working like the recursive.

SetTimeout Function will be called once, but if i used ajax function inside it. Its working recursively.

 var pathname = window.location.pathname;
 setTimeout(function(){
   $('body').load(pathname + '#examplediv');
 },60000);

How to stop calling recursively for ajax load?

From the conversation in comments I have guess a solution. It may be the exact solution for you. But some time will work for others. When I loaded a page named "ABC" through Ajax by clicking a button/link. And from that "ABC" page calling the $('body').load(url). The $('body').load(url) was as many times as I clicked the button/link. Reading from the internet I learned I need unbind the event I created. So I used this just loading the page by ajax. So, I just used method. And it's solved my problem.

$("body").unbind(); 
var pathname = window.location.pathname;
 setTimeout(function(){
   $('body').load(pathname + '#examplediv');
 },60000);

The issue is that you're trying to load a specific element inside a file through Ajax. That's not possible. Ajax loads the entire file you're pointing it to. In your case, the file is your own index file, which also includes the setTimeout function. Hence it keeps on reloading every minute.

To solve this issue, create a new file like popup.html for example. Copy the code inside #examplediv towards this new file. Then remove it from your index file. Now use:

var pathname = window.location.pathname;
setTimeout(function(){
    $('body').load(pathname + '/popup.html');
},60000);

Ajax will now load popup.html after 1 minute (which only contains the code from #examplediv ) into your body element instead of your entire own index file. That will solve the problem.

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