最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

timer - Javascript - setTimeout undefined? - Stack Overflow

programmeradmin0浏览0评论

For a reason that I cannot fathom, the following function doesn't seem to work.

function timerTick()
{
    var t=setTimeout(timerTick,1000);
}

Everything should be working, but when I call the function, the console simply says 'undefined'.

Ideas?

For a reason that I cannot fathom, the following function doesn't seem to work.

function timerTick()
{
    var t=setTimeout(timerTick,1000);
}

Everything should be working, but when I call the function, the console simply says 'undefined'.

Ideas?

Share Improve this question asked Aug 19, 2011 at 11:55 help mehelp me 91 silver badge2 bronze badges 6
  • 1 Why are you assigning the value to a var that never gets referenced again? Do you mean to return the result of setTimeout instead? – Andrzej Doyle Commented Aug 19, 2011 at 11:57
  • The console output must e from somewhere else, the function is perfectly valid. – David Hellsing Commented Aug 19, 2011 at 11:58
  • Add alert('i am called'); inside timerTick(). If you are calling it from the console then 'undefined' is correct behaviour, since the function call produces no return object. – arunkumar Commented Aug 19, 2011 at 11:59
  • setTimeout returns a timeout ID, which can be used to clear the timeout. Are you trying to find out how many milliseconds the setTimeout has left? – Alex Commented Aug 19, 2011 at 12:00
  • I'm trying to make an recursively looping function. I added the alert - it pops up once, then the console says 'undefined' and it never shows again. – help me Commented Aug 19, 2011 at 12:01
 |  Show 1 more ment

2 Answers 2

Reset to default 5

Everything IS working. What you're seeing is the return value of the invokation of timerTick itself which, as it stands, does not have a return statement and whose return value will thus be undefined. (The local variable t is not returned automatically!)

If you add a

console.log( "It's me. Again!" );

inside timerTick and call it you'll be seeing it every second in the console as expected.

EDIT: Typo in code and clarification: The return value of functions not invoked from the console, such as through setTimeout or setInterval, will not be printed to the console.

Everything should be working, but when I call the function, the console simply says 'undefined'.

Ideas?

May be your past this code into console and press enter (for example, in Chrome)? In this case console says 'undefined'. If your need to run function timerTick try next: 1)

function timerTick()
{
    console.info('i am called');
    var t=setTimeout(timerTick,1000);
}
timerTick();

or 2)

(function timerTick()
{
    console.info('i am called');
    var t=setTimeout(timerTick,1000);
})();
发布评论

评论列表(0)

  1. 暂无评论