0

hi I want to use 'this' variable in setInterval in a jquery function I write '// this code don't work' after don't worked line

 (function($)
            {
                $.fn.rotate=function () {
                    var counter=0;
                    var timer=setInterval(function () {
                        counter++;
                        var transform='rotate('+counter+'deg)';
                        $(this).css('transform',transform); // this code dont work
                        if(counter>=300)
                            clearInterval(timer);
                    },1);
                    return this;
                };
                $('#socialNetworks i').rotate();
            }(jQuery))

thanks Alot

good guy
  • 35
  • 6
  • yes but I don't understand that topic please send the answer with my code, my native language is not English and I don't understand that topic – good guy Aug 04 '18 at 17:40
  • The TL;DR is that the “callback” function passed to `setInterval` is called with `this` in the context of `setInterval`. You should either use an arrow function (`=>`) if possible, or use [`bind`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) to change the function’s `this` to the `this` in which it’s syntactically defined. Try to find documentation on how JavaScript’s `this` works in your native language. – Andrew Marshall Aug 04 '18 at 17:59

1 Answers1

-2

Using the arrow function when defining the function maintains the this context in which the function has been called. Thus you would be able to access this inside the function correctly.

( $ => {
    $.fn.rotate=function () {
        var counter=0;
        var timer=setInterval(function () {
            counter++;
            var transform='rotate('+counter+'deg)';
            $(this).css('transform',transform); // this code dont work
            if(counter>=300)
                clearInterval(timer);
        },1);
        return this;
    };
    $('#socialNetworks i').rotate();
})(jQuery)
Anshul Bansal
  • 1,833
  • 1
  • 13
  • 12
  • Where is the explanation that suggests how answer solves problem. It definitely doesn't. Code only answers with no explanation are somewhat useless. See [answer] – charlietfl Aug 04 '18 at 17:52