0

I have tried different things but I do seem to be looking something over that is too obvious. Trying to use the value a function(method) returns inside an object and use it in another method with setTimeout within that same object.

This is the html:

<h1>3000</h1>

The javascript (jQuery in this case):

    var foo = { 
        getValue: function() {
            var h1Text = $('h1').text();
            h1Text = parseInt(h1Text);
            return h1Text;
        }, 
        useValue: function() {
            var time = this.getValue();
            var alertIt = alert('Hello');
            setTimeout(alertIt,time);
        } 
    };
    foo.useValue();
    // log shows correct value
    console.log(foo.getValue());
    // returns a number
    console.log(typeof(foo.getValue()));

The alert does show up, but on load rather than using those 3 seconds. It does log the correct value and also says it's a number so I'm really not sure what I am doing wrong. Any help is appreciated. Thanks

2 Answers 2

1

In useValue() you call alert('Hello'), so it's executed immediately and the result is stored in alertIt variable. You should put it inside the function like this, as setTimeout expects a function as a first parameter:

var alertIt = function() {
    alert('Hello');
}

setTimeout(alertIt,time);
Sign up to request clarification or add additional context in comments.

Comments

1

setTiimeout expects function and not variable. Also var alertIt = alert('Hello'); this will return undefined.

Note: var a = function() will call it and assign return value. To assign a function to a variable with parameter, use .bind

Try alert.bind(null, "hello");

For demo purpose, I have hardcoded value of delay and commented getValue code.

var foo = {
  getValue: function() {
    //var h1Text = $('h1').text();
    //h1Text = parseInt(h1Text);
    return true// h1Text;
  },
  useValue: function() {
    var time = 3000//this.getValue();
    var alertIt = alert.bind(null,'Hello');
    setTimeout(alertIt, time);
  }
};
foo.useValue();
// log shows correct value
console.log(foo.getValue());
// returns a number
console.log(typeof(foo.getValue()));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.