最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - JavaScript setTimeout not working - Stack Overflow

programmeradmin1浏览0评论

I can't understand. In Chrome debugger it works, but when I turn it off and refresh the page, my div is clear.

<script type="text/javascript">
  $(document).ready(function() {
    function banner_change(span) {
      if ($(span).hasClass('show')) {
        $(span).removeClass('show');
      }
    }

    $('div#spec_banner span').each(function () { 
      if (!$(this).hasClass('show')) {
        $(this).addClass('show')
      }
      setTimeout(banner_change(this), 5000);
    });
  });
</script>

Thank you for answering.

I can't understand. In Chrome debugger it works, but when I turn it off and refresh the page, my div is clear.

<script type="text/javascript">
  $(document).ready(function() {
    function banner_change(span) {
      if ($(span).hasClass('show')) {
        $(span).removeClass('show');
      }
    }

    $('div#spec_banner span').each(function () { 
      if (!$(this).hasClass('show')) {
        $(this).addClass('show')
      }
      setTimeout(banner_change(this), 5000);
    });
  });
</script>

Thank you for answering.

Share Improve this question asked Nov 10, 2013 at 7:14 Gregory TeslerGregory Tesler 131 silver badge4 bronze badges 1
  • I understand the problem. setTimer sends function to the end of the script, so jquery.each isn't working. – Gregory Tesler Commented Nov 10, 2013 at 9:02
Add a ment  | 

4 Answers 4

Reset to default 3

several problems , syntax and scope

When using setTimeout without an anonymous function, syntax is:

setTimeout(banner_change, 5000); /* no () */

To pass arguments need to do:

setTimeout(function(){
      banner_change(this);
}, 5000);

But also, back to scope, this has lost context inside setTimeout ( is now likely window) so need to assign to variable outside of setTimeout

$('div#spec_banner span').each(function () { 
  if (!$(this).hasClass('show')) {
    $(this).addClass('show')
  }
    var span =this
  setTimeout(function(){
      banner_change(span);
  }, 5000);
});

This is an issue:

  setTimeout(banner_change(this), 5000);

You're actually calling banner_change here - try

  setTimeout(function(){
      banner_change('div#spec_banner span');
  }, 5000);

The call you were originally doing was executing banner_change immediately and passing the return value to setTimeout

you need to pass function reference not function invocation result.

setTimeout( $.proxy(banner_change, this), 5000);

$.proxy wrapper for the function reference will ensure your function is invoked with the "this" context.

get the function out of document ready for it to work properly

发布评论

评论列表(0)

  1. 暂无评论