Reputation: 33
I'm a beginner in javascript. I need to add one function in my web application, in this function in I have added one task. this task depends on a timer, after 35 seconds it will be automatically started. but the thing is if the user doesn't want to wait for 35 seconds then it will be starting before 35 seconds. user clicks on the start button to call function and it will be task start.
if the user waits for 35 seconds then the task will be an automatic start.
This is my function
setTimeout(
function hello() {
console.log('Hello User')
}, 35000);
<button onclick="hello()">Click me to start</button>
this code is work but the user clicks on the start button to call function. then after 35 seconds to repeatedly automatically task starts.
Upvotes: 3
Views: 47
Reputation: 12629
You can use clearTimeout
like below inside hello
function. Assign return value from setTimeout
to any object
. And you can cancel a timeout
with clearTimeout(object)
.
Also define hello
outside setTimeout
. As setTimeout
accepts callback
function as parameter you can simply use hello
without ()
as parameter
like setTimeout(hello, 5000);
. Or you can define like setTimeout(function() { hello(); }, 5000)
.
As your comment if you want to call another function after 10 seconds, you can again use setTimeout(nextTask, 10000, 'This is parameter');
. I have shown how to pass parameter also with setTimeout
.
If you want clearTimeout
for next function call also then define global variable to hold return value of setTimeout(nextTask, 10000, 'This is parameter');
and use clearTimeout(timeoutNextTask);
. Otherwise no need for it.
Try it below.
function hello() {
console.log('Hello User');
clearTimeout(timeout);
timeoutNextTask = setTimeout(nextTask, 10000, 'This is parameter');
}
function nextTask(x) {
clearTimeout(timeoutNextTask);
console.log(x);
}
var timeoutNextTask;
var timeout = setTimeout(hello, 5000);
<button onclick="hello()">Click me to start</button>
Upvotes: 2
Reputation: 93
You need to define the function outside the setTimeout. This should work
function hello() {
console.log('Hello User')
}
setTimeout( function() {
hello();
}, 5000)
<button onclick="hello()">Click to start</button>
Upvotes: 1
Reputation: 943625
Named function expressions doesn't implicitly create variables of the same name in the current scope. Only function declarations do that.
Define a function separately to passing it to setTimeout
.
function hello() {
console.log('Hello User')
}
setTimeout(hello, 35000);
Upvotes: 0