setInterval(function, timer) become to infinite loop when click Enter key - javascript

I have my set interval function and its working fine, but sometimes after setintervel trigged and I pressed Enter key some 4 to 5 times and my interval become infinite. can any one help me on this.
Thanks in advance.
code:
/one of the js file/
var intervaltime=setInterval(functionname(), 1000);
functionname()
{
if(pageloaded== "true"){ //pageloaded is coming from one JSP when I click that page.jsp
clearInterval(intervaltime);
}
}
**//page.jps**
<input type="hidden" value="true" id="pageloaded" name="pageloaded" />
page.jsp:
init method I added the hidden variable and to set the value of

First of all, the setInterval Method needs a function as first parameter, not "function()" .
For example :
setInterval(function() {
console.log("hello");
}, 1000);
You can also use the following syntaxe to declare your function ouside the timer :
function yourfunc() {
// ...
}
setInterval(yourfunc, 1000);
Also, I think that what you are trying to do is to stop something when your input is clicked or when your page is loaded. If so, the timer is not a good way to do that. You should use an event listener instead.
I hope it helped

Related

SetInterval loop relatively confusing to me

HTML
<div id="backspace" ng-click="deleteString(''); decrementCursor();">
JS
<script>
$scope.deleteString = function() {
if($scope.cursorPosVal > 0){
//$scope.name = $scope.name - letter;
$scope.name = [$scope.name.slice(0, $scope.cursorPosVal - 1) + $scope.name.slice($scope.cursorPosVal)].join('');
console.log($scope.name);
setTimeout(function(){ setCaretPosition("inputBox", $scope.cursorPosVal); }, 30);
} else {
$scope.cursorPosVal = 1;
}
};
</script>
I am designing an on screen touchscreen keyboard. This is my backspace button. I am going to make it so that when you click and hold the backspace button, it starts removing characters automatically. I don't know where to begin with creating a setInterval, and I know a setInterval is exactly what I need to use here.
If I'm not wrong, you want that while you're keeping your button pressed, a function repeats itself.
You're right with setInterval(). However, the way you manage the event is wrong.
Take a look at this fiddle (It's not your code, but a simple example is the best way to understand):
http://jsfiddle.net/daq9atdd/1/
$(function(){
var interval = null;
$('#myButton').mousedown(function(){
interval = setInterval(function(){
console.log('Hello !');
}, 250);
});
$('#myButton').mouseup(function(){
clearInterval(interval);
});
});
I start the interval when the button is pressed, store it, and clear it when the button is released.
You’re so sure about setInterval.
If browser briefly hangs for whatever reason (say some background task), setInterval would go on queueing your backspace calls until it has some CPU time. This means user may see no change and hold backspace longer than needed, and then see a whole bunch of characters suddenly vanish when browser is back to normal.
Thus by setting a timeout after every call you’re making sure user won’t remove more characters than needed. Might be important if the goal is to improve UX.
Example implementation with AngularJS directives and setTimeout
See also:
setTimeout or setInterval?
noKid’s fiddle updated with setTimeout in mind

Starting, stopping & refreshing timer javascript

I have a little fiddle here where I'm starting/stopping/resetting a javascript timer.
The functionality needs to be a timer runs on a page. When the timer is up, it sends a message, then restarts. The stop button will stop the timer completely.
The fiddle above has the functionality I just described, however I feel like I'm not doing this correctly. Is setTimeout the correct way to create this timer? Should I use setInterval instead?
Secondly, my reset code looks like :
var onReset = function() {
clearTimeout(timerHandle);
onStart();
};
Is there a more elegant way to reset a timer in javascript?
Thanks.
The only improvement I can offer is for you to put it all in an encapsulated object, ask if you want an example. Or if you want to keep the structure you've got then change your onStart function to this to remove a bit of un-needed code.
var onStart = function() {
timerHandle = setInterval(function() {
$("#console").append("timer fired.. <br />");
}, 2000);
};
Fiddle here http://jsfiddle.net/qx6CM/

jQuery: Timeout/Delay with a notification function?

I wrote the following simple function that takes two parameters mostly coming from another function returned with json from the server.
var timing = 10000;
function notificationOutput(type, message) {
console.log('output now!');
var note = $('.notification');
note.css('display', 'none');
if ( type == "success" ) { note.removeClass('warning').addClass('success'); }
if ( type == "warning" ) { note.removeClass('success').addClass('warning'); }
note.find('.message').html(message);
note.slideDown( function() {
note.delay(timing).slideUp();
});
}
All it does is simply sliding down a bar from the top of my page putting out a message (either success or warning). The timing variable is for the notification-bar to stay for 10 seconds. So when the function is triggered I want the bar to slideDown(), hold that position for 10seconds and than slideUp() again.
However right now when the function is triggered there is a weird timeout happening till the notification bar appears. That means when the function is fired the console.log() output I have in there right now is logged immediately in my JS-console but the slideDown() takes a few seconds longer to appear! Why is that?
I want the slideDown() to happen immediately (at the same time as the output now is logged in the console). Why is there a delay happening?
Thanks for your help!
Nothing obvious there. I would try trimming the code down until it slides down as expected. Remove the callback, remove the html-set, remove the success/warning class-setters, select the note-element before outputting to the console, replace the slide with an immediate show, etc.
Also try calling .stop(true,true) on the note first: note.stop(true,true).slideDown();. This is in case it is busy with some other animation and the slide down is being queued.
Try this
note.slideDown().delay(timing).slideUp();
i think that the problem might be in the easing function used by the slideDown which is swing by default (which is logaritmic). try using linear and maybe try using a faster slidedown time
note.slideDown(400, 'linear').delay(timing).slideUp(400, 'linear');
You are not passing a value for duration to slideDown. Try:
note.slideDown(1000, function() {
note.delay(timing).slideUp();
});

jQuery how to constantly check if element is hidden/visible?

I have a couple of HTML5 videos on my website (within a slider), they automatically cycle every x seconds (or when user clicks "next slide").
I want to stop the videos that are actually invisible to user, any ideas how to achieve that?
I was tryng to do something like that, but I guess there's "each" missing and it works after click instead all the time (ok, in fact it doesn't work because "this" is used wrong here I guess, but you get the point, sorry, I'm not a JS-guy at all :():
document.on('click', ".videojs:hidden", function(){
alert('video hidden!');
jQuery(this).player.pause();
});
You might want to look into this:
http://www.west-wind.com/weblog/posts/2008/Sep/12/jQuery-CSS-Property-Monitoring-Plugin-updated
You can then do something like this:
jQuery(".videojs").watch("display,visibility", function() {
if(!jQuery(".videojs").is(':visible'))
{
alert('video hidden!');
jQuery(".videojs").player.pause();
}
});
I think you want to look into using setInterval(). Something like:
var videoInterval = setInterval(function() {
// video check logic here
}, 1000);
The above code will run your video check every second (1000 milliseconds). You can probably also use $( instead of jQuery(. The videoInterval variable will let you use clearInterval() if you need to stop the "loop" of checks for any reason. I believe this code will need to be inside of your $(document).ready(function() {...}) block.

Update html text box while Javascript is running

I have an html file that accepts user inputs then uses Javascript to calculate a value based on those inputs. That result is then displayed in an input box after the program has finished.
What I'd like to do is make it so that when you click on the button to run the javascript, the input box that displays the result will show 'Calculating...' until the calculation finishes (the calculation can take ~5 seconds). However, if I put something like:
document.getElementById('answer').value = 'Calculating...';
at the very top of my Javascript code, it doesn't seem to update the input field whenever it runs. Instead, the program runs and then the result is finally updated in the input field.
Anyone know how I can update the input field when I run the program, then update it again with the result once the program finishes?
Thanks!
EDIT: Here's a better explanation of my code
<td colspan=1 align=left><input id="button" value="Calculate" onclick=calculate(this.form.type.value,this.form.d.value,this.form.c.value,this.form.freq.value)>
<input id="answer" readonly="true">
</td>
</tr>
function calculate(type,d,c,f) {
//Performs some calculation
document.getElementById('answer').value = TS;
}
That is because the event of re-drawing of the answer element doesn't happen until AFTER your JavaScript snippet is done (since the browser schedules these things in a queue).
What you need to do is to have your JavaScript interrupt the queue before the calculation starts:
Update the value to "Calculating" (puts the re-draw on the end of the queue)
Set a timer using setTimeout() for 0 seconds (with the timer launching the calculation code)
When the timer fires off immediately, it will put the call to the calculation code at the end of the queue, after the element re-draw.
<script>
document.getElementById('answer').value = 'Calculating...';
setTimeout( your_calculation(), 0);
</script>
This way, your JavaScript will set the field value, set up the timer and finish. Then next on the queue is the re-drawing of the answer element; and THEN the timer fires off and launches the calculation logic.
You have to use a timeout to allow the interface to refresh before doing the calculation.
document.getElementById('answer').value = 'Calculating...';
setTimeout( function() {
// TODO put your actual calculation statements/function calls here.
// document.getElementById('answer').value = answer;
}, 0 );
It sounds to me that you are setting a value on an element that may not exist on the page yet. Check for the DOM being ready first.
Tutorial: http://www.javascriptkit.com/dhtmltutors/domready.shtml
yean mean on the onclick event?
<script>
function onReady() {
document.getElementById('button').click = function() {
document.getElementById('answer').value = 'Calculating...';
document.getElementById('answer').value = doCalculation();
}
}
</script>
<body unload="onReady()">

Categories