How to use "setTimeout" to invoke object itself

Asked
Active3 hr before
Viewed126 times

9 Answers

object
90%

Why can't I use setTimeout in a javascript object?, GitLab launches Collective on Stack Overflow , Meta Stack Overflow ,Thanks for contributing an answer to Stack Overflow!

Try replacing this line:

setTimeout('this.feedbackTag.removeChild(info)', 5000);

with these two lines:

var _this = this;
setTimeout(function() {
   _this.feedbackTag.removeChild(info);
}, 5000);
load more v
88%

Why can't I use setTimeout in a javascript object?,The parentheses invoke the function instantly. ,I believe that for normal functions, this is set to the window object—regardless of where they are declared. So moving the code into a separate function wouldn't fix the problem.,If you don't need to call myGreatFunction with any arguments, you should be able to pass setTimeout a function reference:

Why can't I use setTimeout in a javascript object?

Message = function() {

   ...
   ...

   this.messageFactory = ...
      this.feedbackTag = document.getElementById('feedbackMessages');

   this.addInfo = function(message) {
      var info = this.messageFactory.createInfo(message); // create a div
      this.feedbackTag.appendChild(info);

      setTimeout('this.feedbackTag.removeChild(info)', 5000);
      // why in here, it complain this.feedbacktag is undefined ??????

   };
}

Thanks for Steve`s Solution, now it will work if the code is as below... because the 'this' before was actually pointing to the function within setTimeOut, it cannot rearch Message.

Message = function() {

   ...
   ...

   this.messageFactory = ...
      this.feedbackTag = document.getElementById('feedbackMessages');

   this.addInfo = function(message) {
      var info = this.messageFactory.createInfo(message); // create a div
      this.feedbackTag.appendChild(info);

      var _this = this;
      setTimeout(function() {
         _this.feedbackTag.removeChild(info);
      }, 5000);

   };
}

But why doesn`t it work if we do this:

Message = function() {

   ...
   ...

   this.messageFactory = ...
      this.feedbackTag = document.getElementById('feedbackMessages');
   // public function
   this.addInfo = function(message) {
      var info = this.messageFactory.createInfo(message); // create a div
      this.feedbackTag.appendChild(info);

      delayRemove(info);

   };
   // private function
   function delayRemove(obj) {
      var _this = this;
      setTimeout(function() {
         _this.feedbackTag.removeChild(info);
      }, 5000);
   }
}
load more v
72%

setTimeout(callback function, delay in milliseconds),setTimeout(callback function, delay in milliseconds, arg1),Note: For a countdown that restarts automatically, executing the callback function several times with a timed break between each execution, please see setInterval().,In this code, callback function is the function to be executed, and the delay is the time delay (in milliseconds) before the callback function is executed. The following example code demonstrates how to use this function:

In this code, callback function is the function to be executed, and the delay is the time delay (in milliseconds) before the callback function is executed. The following example code demonstrates how to use this function:

function greet() {
   alert('Welcome!');
}
setTimeout(greet, 2000); //execute greet after 2000 milliseconds (2 seconds)
load more v
65%

Why can't I use setTimeout in a javascript object?,A neater way is to just pass this as an argument to the function being called in the timeout:,Never pass setTimeout a string, as this invokes eval (which you should only use when necessary). Instead, pass setTimeout a function reference (this can be an anonymous function).,Thanks for Steve`s Solution, now it will work if the code is as below... because the 'this' before was actually pointing to the function within setTimeOut, it cannot rearch Message.

Why can't I use setTimeout in a javascript object?

Message = function() {

   ...
   ...

   this.messageFactory = ...
      this.feedbackTag = document.getElementById('feedbackMessages');

   this.addInfo = function(message) {
      var info = this.messageFactory.createInfo(message); // create a div
      this.feedbackTag.appendChild(info);

      setTimeout('this.feedbackTag.removeChild(info)', 5000);
      // why in here, it complain this.feedbacktag is undefined ??????

   };
}

Thanks for Steve`s Solution, now it will work if the code is as below... because the 'this' before was actually pointing to the function within setTimeOut, it cannot rearch Message.

Message = function() {

   ...
   ...

   this.messageFactory = ...
      this.feedbackTag = document.getElementById('feedbackMessages');

   this.addInfo = function(message) {
      var info = this.messageFactory.createInfo(message); // create a div
      this.feedbackTag.appendChild(info);

      var _this = this;
      setTimeout(function() {
         _this.feedbackTag.removeChild(info);
      }, 5000);

   };
}

But why doesn`t it work if we do this:

Message = function() {

   ...
   ...

   this.messageFactory = ...
      this.feedbackTag = document.getElementById('feedbackMessages');
   // public function
   this.addInfo = function(message) {
      var info = this.messageFactory.createInfo(message); // create a div
      this.feedbackTag.appendChild(info);

      delayRemove(info);

   };
   // private function
   function delayRemove(obj) {
      var _this = this;
      setTimeout(function() {
         _this.feedbackTag.removeChild(info);
      }, 5000);
   }
}
load more v
75%

There is another way to use setTimeout(): you can call it recursively to run the same code repeatedly, instead of using setInterval().,Cooperative asynchronous JavaScript: Timeouts and intervals,Cooperative asynchronous Java​Script: Timeouts and intervals,Now, you can pass the name of the person into the setTimeout() call as a third parameter:

let myGreeting = setTimeout(() => {
   alert('Hello, Mr. Universe!');
}, 2000);
load more v
40%

A call to setTimeout returns a “timer identifier” timerId that we can use to cancel the execution.,To cancel the execution, we should call clearTimeout/clearInterval with the value returned by setTimeout/setInterval.,Nested setTimeout calls are a more flexible alternative to setInterval, allowing us to set the time between executions more precisely.,Nested setTimeout allows to set the delay between the executions more precisely than setInterval.

let timerId = setTimeout(func | code, [delay], [arg1], [arg2], ...)
load more v
22%

where expression is the JavaScript code to run after timeout milliseconds have elapsed.,This is an example of JavaScript automatic popup closing after 10 seconds with countdown,,JavaScript features a handy couple of methods of the window object: setTimeout() and setInterval(). These let you run a piece of JavaScript code at some point in the future. In this tutorial we’ll explain how these two methods work, and give some practical examples.,window.setTimeout() allows you to specify that a piece of JavaScript code (called an expression) will be run a specified number of milliseconds from when the setTimeout() method was called. The general syntax of the method is:

window.setTimeout() allows you to specify that a piece of JavaScript code (called an expression) will be run a specified number of milliseconds from when the setTimeout() method was called. The general syntax of the method is:

setTimeout(expression, timeout);

Here’s a simple example:

<input type="button" name="clickMe" value="Click me and wait!" onclick="setTimeout('alert('Surprise!')', 5000)" />

In the above simple example we embedded the entire code for our JavaScript alert box in the setTimeout() call. More usually, you’d call a function instead. In this next example, clicking a button calls a function that changes the button’s text colour to red. At the same time, this function also sets up a timed function using setTimeout() that sets the text colour back to black after 2 seconds:

<script type="text/javascript">

function setToRed ( )
{
  document.getElementById("colourButton").style.color = "#FF0000";
  setTimeout ( "setToBlack()", 2000 );
}

function setToBlack ( )
{
  document.getElementById("colourButton").style.color = "#000000";
}

</script>

<input type="button" name="clickMe" id="colourButton" value="Click me and wait!" onclick="setToRed()"/>

Sometimes it’s useful to be able to cancel a timer before it goes off. The clearTimeout() method lets us do exactly that. Its syntax is:

clearTimeout(timeoutId);

For example, the following code sets up an alert box to appear after 3 seconds when a button is clicked, but the visitor can click the same button before the alert appears and cancel the timeout:

<script type="text/javascript">

var alertTimerId = 0;

function alertTimerClickHandler ( )
{
  if ( document.getElementById("alertTimerButton").value == "Click me and wait!" )
  {
    // Start the timer
    document.getElementById("alertTimerButton").value = "Click me to stop the timer!";
    alertTimerId = setTimeout ( "showAlert()", 3000 );
  }
  else
  {
    document.getElementById("alertTimerButton").value = "Click me and wait!";
    clearTimeout ( alertTimerId );
  }
}

function showAlert ( )
{
  alert ( "Too late! You didn't stop the timer." );
  document.getElementById("alertTimerButton").value = "Click me and wait!";
}

</script>

<input type="button" name="clickMe" id="alertTimerButton" value="Click me and wait!" onclick="alertTimerClickHandler()"/>

The setInterval() function is very closely related to setTimeout() – they even share similar syntax:

setInterval(expression, interval);

So when should you use it? Essentially, if you ever find yourself writing code like:

setTimeout("doSomething()", 5000);

function doSomething() {
   // (do something here)
   setTimeout("doSomething()", 5000);
}

…then you should probably be using setInterval() instead:

setInterval("doSomething()", 5000);

function doSomething() {
   // (do something here)
}

Here’s a simple example of setInterval() and clearInterval() in action. When you press a button, the following code displays “Woo!” and “Yay!” randomly every second until you tell it to stop. (I said a simple example, not a useful one.) Notice how we’ve also used a setTimeout() within the wooYay() function to make the “Woo!” or “Yay!” disappear after half a second:

<script type="text/javascript">

var wooYayIntervalId = 0;

function wooYayClickHandler ( )
{
  if ( document.getElementById("wooYayButton").value == "Click me!" )
  {
    // Start the timer
    document.getElementById("wooYayButton").value = "Enough already!";
    wooYayIntervalId = setInterval ( "wooYay()", 1000 );
  }
  else
  {
    document.getElementById("wooYayMessage").innerHTML = "";
    document.getElementById("wooYayButton").value = "Click me!";
    clearInterval ( wooYayIntervalId );
  }
}

function wooYay ( )
{
  if ( Math.random ( ) > .5 )
  {
    document.getElementById("wooYayMessage").innerHTML = "Woo!";
  }
  else
  {
    document.getElementById("wooYayMessage").innerHTML = "Yay!";
  }

  setTimeout ( 'document.getElementById("wooYayMessage").innerHTML = ""', 500 );

}

</script>

<div id="wooYayMessage" style="height: 1.5em; font-size: 2em; color: red;"></div>
<input type="button" name="clickMe" id="wooYayButton" value="Click me!" onclick="wooYayClickHandler()"/>
load more v
60%

Use the window.setTimeout( ) method to invoke a function once after a delay of a number of milliseconds. You essentially set a timer to trigger a function of your choice. The function is referenced as a string, complete with parentheses, as in the following example: ,Once the timer is set, other script processing may proceed as usual, so it is often a good idea to place the setTimeout( ) call as the final statement of a function. ,Another JavaScript method, setInterval( ), operates much like setTimeout( ), but repeatedly invokes the target function until told to stop (via the clearInterval( ) method). The second parameter (an integer in milliseconds) controls the amount of time between calls to the target function. ,The method returns an ID for the time-out operation and should be preserved in a global variable. If, at any time before the delayed function fires, you wish to abort the timer, invoke the clearTimeout( ) method with the time-out ID as the parameter:

Use the window.setTimeout( ) method to invoke a function once after a delay of a number of milliseconds. You essentially set a timer to trigger a function of your choice. The function is referenced as a string, complete with parentheses, as in the following example:

var timeoutID = setTimeout("myFunc( )", 5000);
load more v
48%

If an object’s property value is itself another object, the variable receives that data as an object reference, still connected to its object:,Once the timer is set, other script processing may proceed as usual, so it is often a good idea to place the setTimeout() call as the final statement of a function.,That function is invoked as a parameter to the document.write() method that places the text in the rendered page:,Use the window.setTimeout() method to invoke a function one time after a delay of a number of milliseconds. You essentially set a timer to trigger a function of your choice. In its most common form, the function is referenced as a string, complete with parentheses, as in the following example:

	var myVar = someValue;
	function myFunction() {
	   var myFuncVar = someValue;
	   ...
	}
load more v

Other "object-undefined" queries related to "How to use "setTimeout" to invoke object itself"