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

javascript - Onclick reset setInterval - Stack Overflow

programmeradmin1浏览0评论
<!DOCTYPE html>
<html>
<head>
<script>

function timer(x) {
    if (x == 1) {
        //reset timer 
        }
    var i = 0;
    var timer = setInterval(function() {

        var x = document.getElementById("demo").innerHTML = i;
        i = i + 1;

    }, 500);
}

</script>
</head>
<body>


<p id="demo">hello</p>

<button type="button" onclick="timer(0)">change</button>

<button type="button" onclick="timer(1)">reset</button>

</body>
</html> 

I want to reset timer onclick . e.g. if setIntervaltime is set to 5 sec and 3 seconds are elapsed ,after that if some on click on reset button it should start gain from 5 seconds.How to do this.

<!DOCTYPE html>
<html>
<head>
<script>

function timer(x) {
    if (x == 1) {
        //reset timer 
        }
    var i = 0;
    var timer = setInterval(function() {

        var x = document.getElementById("demo").innerHTML = i;
        i = i + 1;

    }, 500);
}

</script>
</head>
<body>


<p id="demo">hello</p>

<button type="button" onclick="timer(0)">change</button>

<button type="button" onclick="timer(1)">reset</button>

</body>
</html> 

I want to reset timer onclick . e.g. if setIntervaltime is set to 5 sec and 3 seconds are elapsed ,after that if some on click on reset button it should start gain from 5 seconds.How to do this.

Share edited Aug 16, 2013 at 6:58 putvande 15.2k3 gold badges36 silver badges51 bronze badges asked Aug 16, 2013 at 6:27 user2137186user2137186 8376 gold badges23 silver badges39 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7
  1. Keep the return value of setTimeout somewhere that you can get it again (currently you are storing it in a local variable, so it goes away when the function ends)
  2. Call clearTimeout(timer);
  3. Call setTimeout with whatever arguments you want again.

As already Quentin mentioned, use clearInterval to solve your problem.

Wrap it within an if.else.. statement like

if(x == 1) {
   clearTimeout(timeout);
}
else {
    timeout = setInterval.....  // otherwise even after resetting
                                // it will continue to increment the value
}

Complete Code:

var timeout;  // has to be a global variable
function timer(x) {
    var i = 0;
    if (x == 1) {
        clearTimeout(timeout);
        document.getElementById("demo").innerHTML = i;
    } else {
        timeout = setInterval(function () {
            var x = document.getElementById("demo").innerHTML = i;
            i = i + 1;
        }, 1000);
    }
}

JSFiddle

发布评论

评论列表(0)

  1. 暂无评论