Reputation: 3314
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?
Upvotes: 0
Views: 75
Reputation: 160853
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.
Upvotes: 1
Reputation: 781068
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?
Upvotes: 1