Ayush Bahuguna Ayush Bahuguna - 24 days ago 8
Javascript Question

This keyword inside a setTimeout function, which is nested under a on() method. And it is not working

$("ul").on("click", ".start", function() {
console.log("started");
var timeInput = $(this).parent().children('.time');
var timeInputValue = timeInput.val();
var milliSeconds = Number(timeInputValue)*60*1000;
console.log(milliSeconds);
setTimeout(function(){
alert("Time Over");
$(this).parent().children('.task').toggleClass("completed");
}
, milliSeconds);
})


....................................................................

<ul>
<li><span class="delete">X</span> <span class="start">S</span> <span class="task">Code ToDo</span></li>
<li><span class="delete">X</span> <span class="start">S</span> <span class="task">Read two books</span></li>
<li><span class="delete">X</span> <span class="start">S</span> <span class="task">Run</span></li>
</ul>


I know I am using the
this
keyword wrong inside the setTimeout function, but I want to access,the element with class
.task
respective to the
start
.

How do I do that?

The alert method is working, but the toggleClass is not working.

Answer

You could use arrow function to do that,

setTimeout(() => {
   alert("Time Over");
   $(this).parent().children('.task').toggleClass("completed");
 }, milliSeconds);

If you are writing your code in ES5 then use the 3rd parameter of setTimeout,

 setTimeout(function(_this){
   alert("Time Over");
   $(_this).parent().children('.task').toggleClass("completed");
 }, milliSeconds, this);
Comments