0

How can I clear this timeout:

var timeout = setTimeout(function() {
    window.setTimeout(arguments.callee, 1000);
}, 1000)

clearTimeout(timeout) don't working..

Valera Checha
  • 294
  • 4
  • 16
  • instead of using `window.setTimeout` have you tried changing it to `timeout = setTimeout( .. )` in the function? – Patrick Barr Jun 08 '17 at 13:50
  • You may want to read [this answer to the question of why `arguments.callee` was removed from recent versions of ECMAScript](https://stackoverflow.com/a/235760/215552). – Heretic Monkey Jun 08 '17 at 13:52
  • @PatrickBarr Why would that make any difference? –  Jun 08 '17 at 13:54
  • What do you want to achieve? You have timeout inside timeout :) I think you can make it simpler. Try add clearTimeout(timeout); console.log('been in this line!'); You will know if your code has been entered or not. – Arkadiusz Raszeja Jun 08 '17 at 13:56
  • 1
    You're only clearing the first timeout, not the inner timeout – Heretic Monkey Jun 08 '17 at 13:57

3 Answers3

4

You're setting timeout to the result of the first call to setTimeout, but not any following calls. You probably want

var timeout;

timeout = setTimeout(function() {
  timeout = window.setTimeout(arguments.callee, 1000);
}, 10);

clearTimeout(timeout);

But this would be better written as

function iter() {
  timeout = setTimeout(iter, 1000);
}
1

Store the timeout in a variable that is outside of the scope of the recursion. Also avoid using arguments.callee due to IE's limitations. You can check a working fiddle here.

var timeout = null;

function updateTimeout() {
    timeout = setTimeout(updateTimeout, 1000)
    console.log('hoi')
}

// Start the timeout
updateTimeout();
Remy Kabel
  • 946
  • 1
  • 7
  • 15
0

You need to reassign timeout each time you set new timeout. And get rid of arguments.callee. Try this working example:

<button onclick="myFunction()">Try it</button>
<button onclick="myStopFunction()">Stop the alert</button>

<script>
var timeout;

function myFunction() {
    timeout = setTimeout(function timerHandler() {
        timeout = setTimeout(timerHandler, 1000);
    }, 1000)
}

function myStopFunction() {
    clearTimeout(timeout);
}
</script>
sasha_gud
  • 1,635
  • 13
  • 18