I have this code:
function functionName(){
// blablabla
// dosomething
setTimeout(functionName, 5000)开发者_如何学Go;
}
Well i want to make it if a user presses a button that the function stops replying itself... So that the code becomes
function functionName(){
// blablabla
// dosomething
}
and when he presses a button again that it starts again...
function functionName(){
// blablabla
// dosomething
setTimeout(functionName, 5000);
}
How can i do that (with jquery) ?
Greetings
setTimeout
returns an access-id. That id can be used to call clearTimeout()
which stops the current timeout and therefore ends your "functional-loop";
function functionName() {
if( this.tID ) {
clearInterval(tID);
delete this.tID;
}
// do something
this.tID = setTimeout(functionName, 5000);
}
this
would refer the window
object called just like that. Probably a better idea to use your own namespace to store the id.
Its pretty simple you can use toggle() from JQuery and pass it two methods. One that starts the function and the other that stops the timeout.
var timeoutId;
function functionName(){
// blablabla
// dosomething
timeoutId = setTimeout(functionName, 2000);
}
$(document).ready(function(){
$('#myButton').toggle( function() {
functionName();
}, function() {
clearTimeout(timeoutId);
});
});
To stop the timer you can use clearTimeout
.
var timerId = setTimeout(functionName, 5000);
clearTimeout(timerId);
As for the logic to run a function you can just check to see which button was clicked.
I wasn't 100% clear on what you were looking for so this will at least answer your question as to how to stop a timer.
Here's one way to set up a toggling function to alternate the setTimeout action from on to off:
(function toggler() { // don't pollute the global scope
var temp;
var running = false;
var myfunc = function() {
do_your_stuff_here(); // a pulsing red box in the Fiddle example
running = true;
temp = setTimeout(myfunc, 1000);
}
$('#toggle').click(function(e) { // toggler control is a link
e.preventDefault();
if (running) {
clearTimeout(temp); // turn it off
running = false;
} else {
myfunc(); // or turn it on
}
});
myfunc(); // kickstart it
})();
Here's a working fiddle: http://jsfiddle.net/redler/XKTW9/
精彩评论