0
var interval = setInterval(function (){
    console.log("Hello world");
}, 1000);

var thing = interval;
console.log(thing);
clearInterval(interval);
console.log("interval cleared");
console.log(thing);

thing is printed differently before and after clearing interval and I can't understand why. Halp pls?

Edit: Sorry, I should've been clearer. I'm using node.js, and this is the output to the above code:

{ _idleTimeout: 1000,
  _idlePrev: 
   { _idleNext: [Circular],
     _idlePrev: [Circular],
     msecs: 1000,
     ontimeout: [Function: listOnTimeout] },
  _idleNext: 
   { _idleNext: [Circular],
     _idlePrev: [Circular],
     msecs: 1000,
     ontimeout: [Function: listOnTimeout] },
  _idleStart: 1394616963526,
  _onTimeout: [Function: wrapper],
  _repeat: true }
interval cleared
{ _idleTimeout: -1,
  _idlePrev: null,
  _idleNext: null,
  _idleStart: 1394616963526,
  _onTimeout: null,
  _repeat: false,
  ontimeout: null }

Why is thing affected by the clearInterval at all?

xdazz
  • 158,678
  • 38
  • 247
  • 274
Jazcash
  • 3,145
  • 2
  • 31
  • 46
  • It prints `1` both times for me. – Barmar Mar 12 '14 at 09:29
  • What is different about the way it's printed? – Barmar Mar 12 '14 at 09:32
  • I should probably note that I'm using node.js. Basically, you'd think that `thing would be unchanged` but actually clearInterval clears thing as well as interval when I only want it to clear interval. So before, it prints the interval in its running/pre-running state and the print after it prints it after it's been cleared when it hasn't, only interval has been cleared. – Jazcash Mar 12 '14 at 09:33

2 Answers2

1

clearInterval(interval); is used to cancel the repeated action which was set up by setInterval.

But in your code, thing is assigned before clearInterval(interval);, so it will not printed differently.

Update:

Things are different in node.js, in nodejs, setInterval returns an Timer object but not a number. So clear interval will clear thing too, because they refer to same object.

xdazz
  • 158,678
  • 38
  • 247
  • 274
1

The two variables interval and thing both refer to the same Timer object. When you call clearInterval, it modifies that object, and this is what console.log shows.

It's similar to the following code:

var obj1 = { a : 3 };
var obj2 = obj1;
obj1.a = 4;
console.log(obj2);

This will log { a : 4 }. If you want the two variables to refer to different objects, you need to clone the object; see

What is the most efficient way to deep clone an object in JavaScript?

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612