GEspinha GEspinha - 6 months ago 34
Javascript Question

JQuery toggleClass on setInterval not working

I have the following code:

FIDDLE

$(document).ready(function() {
$('button').each(function(index){
var time = index * 1000;
setInterval(function(){
$(this).toggleClass('one two');
}, time);
});
});


This should cycle between two classes under the set interval time, but its not working. Why?

Answer

Your code does not work because JavaScript is using a concept called lexical scoping. This defines how variable names are resolved in nested functions.

In your case $(this) is not what you think it is. this is bound to setInterval as you pass a anonymous function to setInterval. One of the most important concepts in JavaScript is how scope binds to "this".

Learn more about scoping

  1. http://javascriptplayground.com/blog/2012/04/javascript-variable-scope-this
  2. https://spin.atomicobject.com/2014/10/20/javascript-scope-closures

Working example

https://jsfiddle.net/00w2ythq/1/

$('button').each(function(index){
    var time = index * 1000;
    var button = $(this); // this is bound to .each()

    setInterval(function(){
        // scope changed, this is bound to window
        button.toggleClass('one');
    }, time);
});