Search code examples
javascripthtmlmatchaddress-bar

setInterval not working as expected


$(document).ready(function(){
  $(window).load(function(){
        $('#background_cycler').fadeIn(1500);//fade the background back in once all the images are loaded

      // run every 7s  
      if(typeof window.chrome != "object") {
                setInterval('cycleImages()', 60000);  
      } else {
                setInterval('cycleImages()', 60000);  
      }

      var urlvid = location.href.match(/vid/i);
      if (urlvid) {
                setInterval('cycleImages()', 70000000);  
      }
        var browserName=navigator.appName; if (browserName=="Microsoft Internet Explorer") { setInterval('cycleImages()', 7000); }

This script should change the amount of time that background images switch for different browsers. I need this because Firefox and Chrome usually lag when changing images in background. IE does not do so. This gets really worse, when watching videos so I'd like to check for /vid/ in the address bar and set the changing time to (almost) never. The thing is, it still changes every 60s on this link in Chrome and Firefox. Any ideas what I am doing wrong here?


Solution

  • You setup intervals twice. You need reorder your code or clear prevoius interval. Every call to setInterval create repeated timer, that calls your function.

    var urlvid = location.href.match(/vid/i);
    if (urlvid) {
      setInterval(cycleImages, 70000000);  
    }else{
      // run every 7s  
      if(typeof window.chrome != "object") {
        setInterval(cycleImages, 60000);  
      } else {
        setInterval(cycleImages, 60000);  
      }
    }
    

    Better way to do this is define timeout as variable, change it according your browser rules, and then call setInterval with it.

    var delay = 6000;
    if(location.href.match(/vid/i)){
      delay = 70000000;
    }
    setInterval(cycleImages, delay);