javascript show override-able message with timeout - javascript

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

Related

Run JS code when user finished typing

I have a lot of input fields with the same class. When the user finishes typing the function doneTyping should run.
I tried this but somehow it doesn't work.
Can I use one function for all the input fields I have?
$(function() {
console.log('ready');
var timer;
var doneTypingInt = 5000;
$('.typing').keyup(function(){
clearTimeout(timer);
if ($('.typing').val()) {
timer = setTimeout(doneTyping, doneTypingInt);
}
});
function doneTyping () {
console.log('function doneTyping');
}
});
what you're looking for is debounce
$('.typing').keypress(_.debounce(yourfunc, 3000))
You basically want to use the keypress function. Your adjusted code:
$(function() {
console.log('ready');
var timer;
var doneTypingInt = 5000;
$('.typing').keypress(function(event){
if(timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(doneTyping, doneTypingInt);
});
function doneTyping () {
console.log('function doneTyping');
}
});
I don't think that you have something wrong in your code, you just have to wait 5 seconds to see the result, and in order to use one function for all inputs with the "typing" class, you should use the bind method as follows:
Javascript code: (Jsfiddle)
$(function() {
console.log('ready');
var timer;
var doneTypingInt = 1000;
$('.typing').keyup(function(){
clearTimeout(timer);
if ($('.typing').val()) {
timer = setTimeout(doneTyping.bind($(this)), doneTypingInt);
}
});
function doneTyping () {
alert('function doneTyping ' + this.val());
}
});

Dynamically added function still running even after remove from DOM

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.

How can I stop custom jQuery function which is running?

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();

Clearing an interval that was set before [duplicate]

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');
});
});

setTimout on loading animation after clicking submit

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
});

Categories

Resources