Javascript scope problem with object and setTimeout
- by Shabbyrobe
I'm trying to make a jQuery plugin that executes a method on a timer. I'd like it to work on multiple elements on a page independently. I've reached a point where the timer executes for each element, but the method called in the setTimeout seems to only know about the last instance of the plugin.
I know I'm doing something fundamentally stupid here, but I'm danged if I know what. I know stuff like this has been asked 8 million times on here before, but I've not managed to find an answer that relates to my specific problem.
Here's a script that demonstrates the structure of what I'm doing.
<html>
<head>
<script type="text/javascript" src="assets/jquery.min.js"></script>
<script type="text/javascript">
var crap = 0;
(function($)
{
jQuery.fn.pants = function(options) {
var trousers = {
id: null,
current: 0,
waitTimeMs: 1000,
begin: function() {
var d = new Date();
this.id = crap++;
console.log(this.id);
// do a bunch of stuff
window.setTimeout(function(self) {return function() {self.next();}}(this), this.waitTimeMs);
},
next: function() {
this.current ++;
console.log(this.id);
window.setTimeout(function(self) {return function() {self.next();}}(this), this.waitTimeMs);
},
};
options = options || {};
$.extend(trousers, options);
this.each(function(index, element) {
trousers.begin();
});
return this;
};
}
)(jQuery);
jQuery(document).ready(function() {
jQuery("div.wahey").pants();
});
</script>
</head>
<body>
<div class="wahey"></div>
<div class="wahey"></div>
</body>
</html>
The output I get is this:
0
1
1
1
1
1
The output I expect to get is this:
0
1
0
1
0
1