开发者

Difference in return order?

In Javascript is there a difference between:

return setTimeout(this._onTimeout, 1000*secs);

and

setTimeout(this._onTime开发者_运维技巧out, 1000*secs);
return;

The former does not always run the timeout, but the latter always does. So it feels like there is a difference, but my google-fu is failing to find the reason.


> return setTimeout(this._onTimeout, 1000*secs);

and

> setTimeout(this._onTimeout, 1000*secs); return;

The former does not always run the timeout, but the latter always does

You have that backwards. If the code executes correctly, the first will always return a reference to the setTimeout that can be used to cancel it. The second will always return undefined. Any other behaviour is not confomrant with ECMA–262.

If you are getting some other behaviour, there are errors in the code or what you have posted isn't what is being run.


If it were being used like this:

var obj = {
  set1 : function(secs) {
    return setTimeout(this._onTimeout, 1000*secs);
  },
  set2 : function(secs) { 
    setTimeout(this._onTimeout, 1000*secs);
    return;
  },
  _onTimeout : function() {
     alert("worked");
  }
};
clearTimeout(obj.set1(1));
clearTimeout(obj.set2(1));

Only the second line would cause _onTimeout to actually fire.


There is absolutely no difference. Try to run this code:

(function() {
    return setTimeout(function(){console.log(1)}, 500);
})();
(function() {
    setTimeout(function(){console.log(2)}, 500);
    return;
})();

return doesn't affect on setTimeout call in JS interpreter.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜