How to correctly reference "this" inside setTimeout() callback?

I implemented the “click” and “dblclick” event handlers on every row of a table. From the debug statements, I can see that it is able to distinguish between “click” and “dblclick” with no problem.

But a new problem comes out with the adding of the setTimeout() function. The “this” should refer to the table row the user click. But when I debug in console, it refers to the window object.

How to have “this” refer to the table row the user clicks?

All the codes were working with no problem with “this” reference before adding the setTimeout() function. I need the setTimeout() function because I need to have both the “click” and “dblclick” event handlers.

Your help will be greatly appreciated.

for (let i = 1; i < trs.length; i++) {
  // Add click event handler
  trs[i].addEventListener('click', function (event) {
    if (event.detail === 1) {
      var record =;
      timer = setTimeout(function () {
        document.title = "testing click";
        // Add new row to the front of machine documentation table
        var newRow = {
          value: {
            "company": { type: "SINGLE_LINE_TEXT", value: this.children[0].innerText },
            "modelno": { type: "SINGLE_LINE_TEXT", value: this.children[1].innerText },
            "serialno": { type: "SINGLE_LINE_TEXT", value: this.children[2].innerText },
            "notes": { type: "SINGLE_LINE_TEXT", value: "" }

        // Unshift to add new row to the front of machine documentation table

      }, 200);
  }); // addEventListener click

  // **** Add double click event handler
  trs[i].addEventListener('dblclick', function (event) {
    document.title = "testing dblclick";
    var record =;
    console.log("dblclick" + this.children[0].innerText + this.children[1].innerText + this.children[2].innerText);;
  }); // addEventListener dbclick
} // for

Hi annaylee,


The standard method would be to store the data in a variable outside the setTimeout function and then refer to it from the variable in the setTimeout function.

document.getElementsByClassName('subtable-gaia')[0].addEventListener('click', function (event) {

console.log("No.1", this);
var self = this;

timer = setTimeout(function () {

console.log("No.2", this);
console.log("No.3", self);

}, 200);


Hopefully, this helps.