Rahul Singh
Rahul Singh

Reputation: 1632

setInterval can't access variable?

I have a JavaScript function named showchild(pgid). I have called function on document ready...

$(document).ready(function()
{
     var pgid = $('#hiddenuserkey').val();
    //alert(pgid);
     showchild(pgid);
     setInterval("showchild(pgid)",1000);
});

Upvotes: 1

Views: 1793

Answers (1)

ThiefMaster
ThiefMaster

Reputation: 318808

You are using it in the worst possible way - passing a string.

Use the following code instead:

setInterval(function() {
    showchild(pgid);
}, 1000);

When passing a string, it will be evaluated in the global context without having access to any non-global variables. By passing a function (the preferred way) all accessible variables are preserved in the function's closure so pgid is defined inside that function when it's called.

Upvotes: 7

Related Questions