简体   繁体   中英

Why isn't setTimeout working in this function?

I've created a function that generates tabs. It works by taking element IDs as parameters, and then generates an event listener, which then responds to click events of any of the elements. It's a little complicated, so I'll just post it:

function toggleTabs() {
  var panel = [], li = [];
  for(var i = 1, j = arguments.length; i <= j; i++) {
    li[i] = document.getElementById(arguments[i - 1]);
    panel[i] = 'panel' + i;
  }  
  document.getElementById('toggle').addEventListener('mouseup', function(event) {
    var target = event.target.id;
    for(var i = 1, j = li.length; i <= j; i++) {
      if(li[i].id === target) {
        document.getElementById(panel[i]).style.display = 'block';
        setTimeout(function() {
          document.getElementById(panel[i]).style.opacity = '1';
          window.alert('fired');
        }, 500);
        li[i].className = 'active';
      } else if(target.substring(0,3) === 'tab'){
        document.getElementById(panel[i]).style.display = 'none';
        document.getElementById(panel[i]).style.opacity = '0';
        li[i].className = null;
      }
    }
  }, false);
}
if(url === '/customers') { toggleTabs('tab-c-featured', 'tab-c-view'); }

As it is, it works, but I want the elements to fade in when it is triggered, which isn't happening despite a transition effecting existing on the elements. I thought this might be because of the display property changing also, overriding the fade-in opacity effect, so I decided to add a timeout effect - but it isn't working. I added a window alert to test it, and for some reason it wont fire, why is this?

thanks

There is possible error. It's necessary to use closures when you create a deferred function calls inside of a cycle. So here is the mistake document.getElementById(panel[i]).style.opacity = '1';

When the function will be called, panel[i] will refers to the last element of the panels list. To avoid this behaviour wrap your calls to closure, eg
setTimeout(function (thePanel) { return function(){ // do whatever you need with thePanel } }(panel[i]), 500);

There is more info about this problem at SO

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