Reputation: 720
When clearTimeout(fun);
is added right below setTimeout
function it works as it should, But I couldn't encounter whats wrong with this code.
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>
<button onclick="myfunction()">click me</button>
<script>
function myFunction() {
var fun = setTimeout(function(){ alert("Hello"); }, 3000);
}
function myfunction(){
clearTimeout(fun);
}
</script>
</body>
</html>
Upvotes: 0
Views: 427
Reputation: 56499
that's because the identifier fun
is only existent within the containing code block.
The solution is you'll need to declare it outside of the functions, this will enable you to use the identifier fun
within both functions.
Also, even though your function identifiers are distinguished by the first 'f'
, it's a good practice to give them meaningful identifiers that can be easily distinguished by the eye.
<!DOCTYPE html>
<html>
<body>
<button onclick="start()">Try it</button>
<button onclick="end()">click me</button>
<script>
var fun;
function start() {
fun = setTimeout(function(){ alert("Hello"); }, 3000);
}
function end(){
clearTimeout(fun);
}
</script>
</body>
</html>
Upvotes: 5
Reputation: 854
fun
as a variable is not accessible within the second myFunction
as it is a variable local to the scope of the first myFunction
. fun
needs to be declared globally - or at the parent level of both functions.
<script>
var fun;
function create() {
fun = setTimeout(function(){ alert("Hello"); }, 3000);
}
function cancel(){
clearTimeout(fun);
}
</script>
As a side note, functions need to have unique names otherwise the second declaration will overwrite the first.
Upvotes: 7