0

i was just going through the code of carasoul.js and came across the following line of code ::

setTimeout(function () {
            that.$element.trigger(slidEvent)
          }, 0)

well its very simple what the above line of code is doing , the below line of code ::

that.$element.trigger(slidEvent)

is executed at an interval of 0 , now my question is , what is the context of this piece of code , if all the author wanted was to run a function/execute a line of code immediately , he could have done it without the settimeout , like so in this case ,

instead of ::

setTimeout(function () {
            that.$element.trigger(slidEvent)
          }, 0)

the author could have just written the following lines of code ::

that.$element.trigger(slidEvent) 

so why the set time out , what is its context ??

below is the entire snippet of code , so that it makes more sense ::

$active
        .one('bsTransitionEnd', function () {

          $next.removeClass([type, direction].join(' ')).addClass('active')
          $active.removeClass(['active', direction].join(' '))
          that.sliding = false 

          setTimeout(function () {
            that.$element.trigger(slidEvent)
          }, 0)
        }) 

the entire code can also be found on git here. (line 156).

to repeat my question , why is setTimeout used when it seems to be doing nothing ?

alex
  • 479,566
  • 201
  • 878
  • 984
Alexander Solonik
  • 9,838
  • 18
  • 76
  • 174

1 Answers1

1

This is done to call the function on the next cycle. I use it when i need to wait for the DOM to refresh or some other event to dispatch in this cycle.

You're adding your function in the setTimeout queue and in the next cycle when the setTimeout queue is checked your method is executed because the time (0) is passed.

Possible duplicate: Why is setTimeout(fn, 0) sometimes useful?

Community
  • 1
  • 1
SharpEdge
  • 1,782
  • 1
  • 10
  • 20