-1

I have a small function:

function showVotingModal(e) {

    var $collector = $("#vote-collector");

    setTimeout(function () {

        $collector.addClass("open");
    }, 5000);

    $collector.find(".description").text($(this).data("desc"));
    $collector.attr("data-id", "15");

}

The idea is to show the #vote-collector panel after a delay of 5 seconds and populate some further data withing the panel.

The above code works, however the code below doesn't.

function showVotingModal(e) {

    setTimeout(function () {
        var $collector = $("#vote-collector");
        $collector.addClass("open");
        $collector.find(".description").text($(this).data("desc"));
        $collector.attr("data-id", "15");

 }, 5000);
    }

In this case the 'description' tag isn't populated.

Can anyone throw some light on whether I'm doing something wrong, or does the timeout function simply does not work this way?

Thanks

John Ohara
  • 2,821
  • 3
  • 28
  • 54

3 Answers3

4

Try to bind the outer scope to the setTimeout,

 function showVotingModal(e) {
    setTimeout(function () {
        var $collector = $("#vote-collector");
        $collector.addClass("open");
        $collector.find(".description").text($(this).data("desc"));
        $collector.attr("data-id", "15");
     }.bind(this), 5000);
 }

Inside setTimeout this will be considered as window by default.

Or you can use the other signature of setTimeout that accepts additional parameters after delay,

 function showVotingModal(e) {
    setTimeout(function (that) {
        var $collector = $("#vote-collector");
        $collector.addClass("open");
        $collector.find(".description").text($(that).data("desc"));
        $collector.attr("data-id", "15");
     }, 5000, this);
 } 
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
2

There is very small mistake in your code you are using this, which is currently pointing to current function scope. you just need to update your function with below code

function showVotingModal(e) {
  var self = this;
  setTimeout(function () {
    var $collector = $("#vote-collector");
    $collector.addClass("open");
    $collector.find(".description").text($(self).data("desc"));
    $collector.attr("data-id", "15");

 }, 5000);
}
Sandeeproop
  • 1,756
  • 1
  • 12
  • 18
1

The issue should be with the code $(this).data("desc")

this will be pointing to different contexts/objects in the 2 cases u've used.

Try using bind for the setTimeout.

Sanjay
  • 111
  • 1
  • 9