blankammo
blankammo

Reputation: 119

How to stop function reload(window.reload) on jquery or javascript?

Source

$(function reload(){
  $.ajax({
    .
    .
    .
    window.setTimeout(reload, 3000);
  });
});

This function reload ajax page on every 3 sec.

I want to make stop button(#stop).

$('#stop').click(function){
   //STOP FUNCTION
});

Please let me know how to make it?

Upvotes: 0

Views: 2061

Answers (3)

voidvector
voidvector

Reputation: 1996

If the source is something you cannot modify, then you would have to do something hacky, like overriding the reload() function:

$('#stop').click(function){
   window.reload = function() {};
});

If this fails because reload() is not under window, then you can actually override window.setTimeout(), but that's highly not recommended.

Upvotes: 0

qiao
qiao

Reputation: 18219

To clear a timeout, first you need to assign the value returned by the setTimeout function to a variable

var timer = setTimeout(...)

then use clearTimeout to clear the timer;

clearTimeout(timer);

you may check out https://developer.mozilla.org/en/DOM/window.clearTimeout for a detailed explanation.

EDITED: In your case, you may either use setInterval and clearInterval instead, or use a boolean flag to indicate whether to reload or not.

var toReload = true;

$(function reload(){
  $.ajax({
    .
    .
    .
    if (toReload) {
      window.setTimeout(reload, 3000);
    }
  });
});

$('#stop').click(function){
   toReload = false;
});

Upvotes: 3

Mujassir Nasir
Mujassir Nasir

Reputation: 1720

var c =0;

$(function reload(){

  $.ajax({
    .
    .
    .

if(c == 0)    
    window.setTimeout(reload, 3000);

  });

});




$('#stop').click(function){

  c =1;

});

Upvotes: 1

Related Questions