-4

I wrote a function that change css background image every 1 second base on interval, and its all working fine, the problem is that now i want to stop the function that switches the background image and the interval setup keep overwriting me.

my code:

  var backgrounds = new Array(
'url(/srv/admin/img/announcement/envelope_blue.png)'
, 'url(/srv/admin/img/announcement/envelope_red.png)'

);

var current = 0;

function nextBackground() {   
    current++;
    current = current % backgrounds.length;
    jQuery("#open_msg_tlbr_img").css('background-image', backgrounds[current]);
    jQuery("#open_msg_tlbr_img").css('width','35px');
    jQuery("#open_msg_tlbr_img").css('height','35px');


}
setInterval(nextBackground, 1000);

jQuery("#open_msg_tlbr_img").css('background-image', backgrounds[0]);    

I tried using : clearInterval();

how do i stop this monster?

user2706762
  • 397
  • 1
  • 3
  • 11
  • 1
    Please look up documentation on functions you're using, before asking questions like this on SO. The [`setInterval` docs](https://developer.mozilla.org/en/docs/Web/API/window.setInterval) have a link to the [function you need](https://developer.mozilla.org/en-US/docs/Web/API/window.clearInterval). – Cerbrus May 27 '14 at 10:08
  • http://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript?rq=1 – Abdennour TOUMI May 27 '14 at 10:10

3 Answers3

2

Use a variable to hold the return value of setInterval and then clear it:

var interval = setInterval(nextBackground, 1000);
clearInterval(interval);
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
1

You are not assigning object returned by setInterval so that you can clear it later, Pass the object returned by setInterval to clear in clearInterval function. Note you would need a global variable to be used in more then one functions.

Assigning object returned by setInterval

intr = setInterval(nextBackground, 1000);

Passing setInterval reference object to clearInterval

clearInterval(intr );
Adil
  • 146,340
  • 25
  • 209
  • 204
1

setInterval() returns an interval ID, which you can pass to clearInterval():

var nxtBckgrnd = setInterval(nextBackground, 1000);

/* later */
clearInterval(nxtBckgrnd );

setInterval()

clearInterval()

Ishan Jain
  • 8,063
  • 9
  • 48
  • 75