开发者

Why does it increase each time?

开发者 https://www.devze.com 2023-02-26 20:23 出处:网络
I want to understand why the number of timer keeps increasing whenever it is in use. Should it start from a fresh number each time?

I want to understand why the number of timer keeps increasing whenever it is in use.

Should it start from a fresh number each time?

And why does it increase 2 or 4 each but not 1?

$(document).ready(function(){
    endAndStartTimer开发者_开发问答();
});

var timer;
function endAndStartTimer() {
  window.clearTimeout(timer);
  //var millisecBeforeRedirect = 10000; 
  timer = window.setTimeout(function(){alert('Hello!');},1000); 
  alert(timer);
}

Do I need window.clearTimeout(timer); inside the function? What would it be wrong if I d

you can try it here.

Thanks.


Some simple facts

  1. You don't have to call clearTimeout before setting one. At least not in the code you provided.

  2. When I run your JSFiddle in FF4 it always reports 2

  3. Timer IDs are generated by Javascript engine implemented in the browser so you don't have much control over it. Whatever it returns is value that you have to use to clear it. I haven't tested it but it may as well be that these ID generators are implement in a different way. Although the simplest (=fastest) way is by simply incrementing the ID of the last timer ID.


The method returns unique timer ID. The only purpose is to give you a handle to use it with clearTimeout. You can't control what id is generated.

0

精彩评论

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