I have a custom jQuery function. When it runs every 5 seconds.
(function($) {
$.fn.mycustomfunction = function() {
interval = setInterval(function() {
console.log("I am running every 5 seconds");
}, 5000);
}
return this;
};
})(jQuery);
$("#container").mycustomfunction();
I have a
clearInterval(interval);
to stop, but I also want to stop the function completely. How can I do that ?
Functions you add to this object will be attached to your object and Simple and naive solution will follow:
(function($) {
$.fn.mycustomfunction = function() {
interval = setInterval(function() {
console.log("I am running every 5 seconds");
}, 1000);
this.stop= function(){
clearInterval(interval);
}
// another function
this.alert = function(msg){
alert(msg)
}
return this;
};
})(jQuery);
to stop use
var feature = $("#container").mycustomfunction();
feature.stop();
Related
This script has been added dynamically. It has a timeout function, means that it runs every 5 seconds.
dynamicjs.php
$(document).ready(function(){
(function( $ ){
$.fn.baslatmesajlari = function() {
setInterval(function(){
console.log("I am running");
}, 5000);
return this;
};
})( jQuery );
});
$("body").baslatmesajlari();
I load this function to a div using;
$("#temporarycontent").load("dynamicjs.php");
And when I do
$("#temporarycontent").empty();
The script is still running. How can I stop it run ?
You can't, you need a handle to the intervalId returned by the setInterval function or provide an API on the plugin in order to destroy it and cleanup after itself. The easiest way would be to attach the state of the plugin to the DOM element on which it was applied.
(function ($) {
const PLUGIN_NAME = 'baslatmesajlari';
function Plugin($el) {
this.$el = $el;
this._timerId = setInterval(function () {
console.log('running');
}, 2000);
}
Plugin.prototype.destroy = function () {
this.$el.removeData(PLUGIN_NAME);
clearInterval(this._timerId);
};
$.fn[PLUGIN_NAME] = function () {
if (!this.data(PLUGIN_NAME)) this.data(PLUGIN_NAME, new Plugin(this));
return this;
};
})(jQuery);
$(function () {
var plugin = $('#plugin').baslatmesajlari().data('baslatmesajlari');
$('#destroy').click(function () {
plugin.destroy();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="plugin"></div>
<button id="destroy">Destroy plugin</button>
You must have a reference to the interval id, then, when you want to stop it's execution, call clearInterval(the_id)
let interval = null //this is the variable which will hold the setInterval id
$(document).ready(function () {
(function ($) {
$.fn.baslatmesajlari = function() {
interval = setInterval(function () {
console.log('I am running')
}, 5000)
return this
}
})(jQuery)
})
$("body").baslatmesajlari()
And then:
$("#temporarycontent").empty();
clearInterval(interval) // it should stop the function.
Hope it helps.
This question already has answers here:
How can I use setInterval and clearInterval?
(5 answers)
Closed 8 years ago.
http://jsfiddle.net/x5MY8/2/
HTML
<div id="easy">easy</div>
<div id="hard">hard</div>
JS
function test(mode) {
var asd = this;
this.mode = mode;
setInterval(function () {
alert(asd.mode);
}, 1000);
}
$(document).ready(function () {
$('#easy').on('click', function () {
var stuff = new test('easy');
});
$('#hard').on('click', function () {
var stuff = new test('hard');
});
});
Upon pressing the easy button, an event launches that alerts easy every second. If I press hard afterwards, it will start another event, and it will alert easy, hard, easy, hard.., but I want it to alert only what was pressed at the moment, so I have to clear the previous interval somehow. How can I do that? Somehow, I need to call clearInterval when a button is pressed on the other object, but I don't really know how to.
http://jsfiddle.net/x5MY8/3/
You need to store and clear the interval like so
var interval;
function test(mode) {
var asd = this;
this.mode = mode;
if (interval) {
clearInterval(interval);
}
interval = setInterval(function () {
alert(asd.mode);
}, 1000);
}
Store it in a variable:
var interval = setInterval(function(){
//your code
},1000);
Now, you can clear using clearInterval:
clearInterval(interval);
clear the value when every clicked
var clear=0;
function test(mode) {
var asd = this;
this.mode = mode;
clear=setInterval(function () {
alert(asd.mode);
}, 1000);
}
$(document).ready(function () {
$('#easy').on('click', function () {
clearInterval(clear);
var stuff = new test('easy');
});
$('#hard').on('click', function () {
clearInterval(clear);
var stuff = new test('hard');
});
});
var message;
function Message(message) {
(function () {
$('#configMsg').html(message);
}());
this.timer = setTimeout(function () {
$('#configMsg').html('');
}, 5000);
}
$('#foo').click(function () {
message = new Message('foo');
});
$('#bar').click(function () {
message = new Message('bar');
});
What I'm trying to do is display message for 5 seconds, but if I display a new message the timer should be reset to 5 seconds.
My theory was that if I overwrite the message var which contains a Message function with a new Message function the old one will be destroyed along with the timer that it contains.
But its not working out, I think the old timer still exists as sometimes a message is displayed for less than 5 seconds.
Here is a fiddle http://jsfiddle.net/sgRrk/
function Message(message) {
var elem = $('#configMsg');
elem.html(message);
window.clearTimeout(elem.data("timer")); //if there is a previous timer, cancel it
elem.data("timer", setTimeout(function () { //store the timer reference to remove
elem.html('');
}, 5000));
}
What about a function that has a private timer and a public messsage() method?
function messager() {
var timer;
return {
message : function(message){
$('#configMsg').html(message);
clearTimeout(timer);
timer = setTimeout(function () {
$('#configMsg').html('');
}, 5000);
}
};
}
var msgr = new messager();
$('#foo').click(function () {
msgr.message('foo');
});
$('#bar').click(function () {
msgr.message('bar');
});
Fiddle THIS!
If you want to overwrite a variable that is part of an object, as in this.timer, don't create new instances of the object on every click, do it the easy way and use the same function, and clear the timeout on subsequest clicks
function message(message) {
$('#configMsg').html(message);
clearTimeout(this.timer);
this.timer = setTimeout(function () {
$('#configMsg').html('');
}, 5000);
}
$('#foo').click(function () {
message('foo');
});
$('#bar').click(function () {
message('bar');
});
FIDDLE
You want to clear your timer each time you create a new message.
var message;
var timer;
function Message(message) {
clearTimeout(timer);
(function () {
$('#configMsg').html(message);
}());
timer = setTimeout(function () {
$('#configMsg').html('');
}, 5000);
}
$('#foo').click(function () {
message = new Message('foo');
});
$('#bar').click(function () {
message = new Message('bar');
});
You need to save a timeout reference and reset it when a new timeout is created:
var message,
timer;
function Message(message) {
(function () {
$('#configMsg').html(message);
}());
if ( typeof timer != 'undefined' ) {
clearTimeout( timer );
delete timer;
}
timer = setTimeout(function () {
$('#configMsg').html('');
}, 5000);
}
$('#foo').click(function () {
message = new Message('foo');
});
$('#bar').click(function () {
message = new Message('bar');
});
Fiddle
I would like to have an animation funciton show for 2 seconds once the submit button is clicked. I am not sure how to put it all together using the setTimeout function
$(window).ready(function () {
"use strict";
var countdown = 2000;
setTimeout(function()){
var startAnimation = function () {//this is what I need to animate for 2 seconds
$(".normal-actions").hide();
$(".execute-actions").show();
};
$("form").attr("action", "url");
$(".btn-submit").on("click", function () {
$("form").submit;
});
});
}
current code (could not put in comments) the page stays in loading and does not redirect:
$(window).ready(function () {
"use strict";
var countDown = 2000;
setTimeout(function(){
$(".normal-actions").hide();
$(".execute-actions").show();
}, countDown);
$("form").attr("action", "url");
$(".btn-submit").on("click", function () {
$("form").submit;
});
});
You never actually called setTimeout and never made an initial change to the UI. You should call it when submit is clicked.
$(window).ready(function () {
"use strict";
var countdown = 2000;
var toggleAnimation = function () {//this is what I need to animate for 2 seconds
$(".normal-actions").toggle(); //toggles between show/hide
$(".execute-actions").toggle();
};
$("form").attr("action", "url");
$(".btn-submit").on("click", function () {
$("form").submit;
toggleAnimation(); //first call start animation to change the UI
setTimeout(toggleAnimation, countdown); //then call startAnimation again after 2 seconds to change it back
});
});
}
$(window).ready(function () {
"use strict";
var countdown = 2000;
$("form").attr("action", "url");
$(".btn-submit").on("click", function () {
//When the button is clicked change class to indicate that the process started
$(".normal-actions").hide();
$(".execute-actions").show();
$("form").submit;
//2 seconds later revert the changes in the classes
setTimeout(function() {
$(".normal-actions").show();
$(".execute-actions").hide();
}, 2000);
});
}
//
// give this a go:
//
function wait( function_, time_out_in_ms ) {
return function () {
var args = Array.prototype.slice.call( arguments ),
target = this;
setTimeout(
function () {
return function_.apply( target, args );
},
time_out_in_ms
);
return this;
};
}
//
// use:
//
var
fn1 = wait(
function () { console.log( this, arguments ); },
3000
);
fn1.call( document, { info : "stuff" } );
fn1(1,2);
//
//
// Document & Window <-- returned imidiately
//
// ... logged after 3 sec:
// Document [Object { info="stuff"}]
// Window [1, 2]
//
Set your animation as the function callback to setTimeout():
setTimeout(function(){
$(".normal-actions").hide();
$(".execute-actions").show();
}, countDown);
Or if you want to reuse your function:
var startAnimation = function () {
$(".normal-actions").hide();
$(".execute-actions").show();
};
setTimeout(startAnimation, countDown);
EDIT: Your form is not submitting because you are not evoking the submit function:
$(".btn-submit").on("click", function () {
$("form").submit(); // <-- open and closed paren
});
I'm developing a chrome plugin that inject a class to every element in the page. But in pages such as facebook or twitter there is content loaded dynamically, so I use this code to check when this conent is loaded:
document.addEventListener('DOMNodeInserted', function() {
console.log('fatto');
}, true);
the problem is that this way, the script is fired every single time a node is inserted. Therefore I'd like to add some kind of limitation. something like: When a node is inserted fire the script and then wait 2 sec.
I'm trying something like this but no success:
var check = 1;
document.addEventListener('DOMNodeInserted', function() {
if(check == 1) {
check = 0;
setInterval( function() {
//do stuff
check = 1;
}, 1000);
console.log('fatto');
}
}, true);
thanks
I've seen this technique referred to as debouncing. Here's an example:
(function() {
var timer;
var doStuff = function() {
timer = null;
alert("Doing stuff");
};
document.addEventListener('DOMNodeInserted', function() {
if (timer) {
window.clearTimeout(timer);
}
timer = window.setTimeout(doStuff, 2000);
}, false);
})();
You can generalize this:
function addDebouncedEventListener(obj, eventType, listener, delay) {
var timer;
obj.addEventListener(eventType, function(evt) {
if (timer) {
window.clearTimeout(timer);
}
timer = window.setTimeout(function() {
timer = null;
listener.call(obj, evt);
}, delay);
}, false);
}
addDebouncedEventListener(document, 'DOMNodeInserted', function(evt) {
alert(evt.target.nodeName + " inserted");
}, 2000);
I'd say:
var timeout;
document.addEventListener('DOMNodeInserted', function() {
startNewTimeout();
}, true);
function startNewTimeout() {
//only if there is no active timeout already
if(timeout === undefined) {
timeout = setTimeout( function() {
timeout = undefined;
//do stuff
}, 1000);
}
}
This script won't delay the execution of //do stuff indefinitely. It will make sure that //do stuff is executed max. 1sec after first DOMNodeInserted event.