User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the JavaScript / DHTML / AJAX section within the Web Development category of DaniWeb, a massive community of 427,732 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 3,906 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our JavaScript / DHTML / AJAX advertiser: Lunarpages Web Hosting

setInterval inside function issue

Join Date: Jun 2006
Location: India
Posts: 6,863
Reputation: ~s.o.s~ is a splendid one to behold ~s.o.s~ is a splendid one to behold ~s.o.s~ is a splendid one to behold ~s.o.s~ is a splendid one to behold ~s.o.s~ is a splendid one to behold ~s.o.s~ is a splendid one to behold ~s.o.s~ is a splendid one to behold 
Rep Power: 23
Solved Threads: 344
Moderator
Featured Poster
~s.o.s~'s Avatar
~s.o.s~ ~s.o.s~ is offline Offline
Lazy, Useless & Apathetic

Re: setInterval inside function issue

  #6  
Apr 17th, 2008
To get around these scope issues, you can either go with the messier and error prone global object solution or make use of the elegant concept of Closures.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
            "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <meta http-equiv"Script-Content-Type" content="text/javascript">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="Expires" content="0"> <!-- disable caching -->
    <title>Example</title>
    <script type="text/javascript">
    function Klass(name) {
      this.name = name;
      this.handle = null;
      this.startTimer = function() {
        this.handle = setInterval(function(obj) {
          return(function() {
            alert(obj.name);
            });
          }(this), 5000);
      }
    var a = new Klass('hello');
    a.startTimer();
    </script>
</head>
<body>  
</body>
</html>
I don't accept change. I don't deserve to live.

Happiness corrupts people.

Failing to value the lives of others cheapens your own.
Reply With Quote  
All times are GMT -4. The time now is 12:30 pm.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC