English 中文(简体)
设置隔interval 方法不工作
原标题:setinterval method not working

I have a button which triggers the function inside set interval every 1 sec. The value of the button changes to stop. When I hit stop I call the clearinterval method. For some reason the clear interval method is not working.

这是我的投入

<input id="trigger" type="button" value="start"/>

我的 js 函数

$(function() {
    $( #trigger ).click(function() {
        var timerId = 0;
        var trigger = $( #trigger ).val();

        if(trigger ==  start ) {
            timerId = setInterval(function() {
                $( #trigger ).val( stop );
                main();
            }, 1000);
        } else if(trigger ==  stop ) {
                clearInterval(timerId);
                $( #trigger ).val( start );                
        }
    });
});
最佳回答

您的定时器ID 定义在单击范围为本地范围 (), 所以当您第二次运行时( 在停止事件中), 它会再次为 0 。 请试一下 。

var timerId = 0;
$(function() {
    $( #trigger ).click(function() {
        var trigger = $( #trigger ).val();

        if(trigger ==  start ) {
            timerId = setInterval(function() {
                $( #trigger ).val( stop );
                main();
            }, 1000);
        } else if(trigger ==  stop ) {
                clearInterval(timerId);
                $( #trigger ).val( start );                
        }
    });
});
问题回答

每次点击# 触发器时, 您正在重新初始化计时rID 。 在单击函数之外移动 va timerlID = 0;





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签