#Attributes becoming undefined when passing methods around

17 messages · Page 1 of 1 (latest)

noble python
#

Hey there!
I'm not much of a JS person so I'm rather confused about what's going on here. I've got this class here ```js
class TypeWriter {
constructor(text, speed) {
this.text = text;
this.speed = speed;
this.idx = 0;
}

        write() {
            if (this.idx < this.text.length) {
                document.getElementById("testing").innerHTML += this.text.charAt(this.idx);
                this.idx++;
                setTimeout(this.write, this.speed + randomness() * 15);
            }
        }
    }

And all is working fine when typing the very first letter, however afterwards I'm getting the error
Uncaught TypeError: Cannot read properties of undefined (reading 'length')
at write (index.html:21:42)
```So seems like when I pass this.write to setTimeout, when the method is next called this is no longer being referenced properly. I'm sure this is just me not really understanding how this works in JS or some odd referencing thing, but if anyone has any suggestions on how I could make this work do let me know.

shadow light
#

You'll need to explicitly bind this to the method you are passing into setTimeout:

setTimeout(this.write.bind(this), this.speed + …)
#

if you don't do this, this will just be bound by regular context rules when the reference to write is called. It will then contain the window object. You can confirm this by doing a console.log(this) at the top of write().

hollow owl
#

You could also do something like this, if I got your code correct 🙂

class TypeWriter {
    constructor(text, speed) {
        this.text = text;
        this.speed = speed;
        this.idx = 0;
    }

    async write() {
        while (this.idx < this.text.length) {
            document.getElementById("testing").innerHTML += this.text.charAt(this.idx);
            this.idx++;
            await this.sleep(this.speed + randomness() * 15);
        }
    }
    
    private sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
}
noble python
hollow owl
noble python
#

Ah true what is the call stack limit in JS

#

Because with what I have in mind if it's anything like Python's recursion limit then yeah I will hit it

hollow owl
noble python
#

Yep that's fair

#

I'll go with the section option

#

*second

#

And I can't type today

#

Nice

#

Anyways

#

Thanks for the help guys