Is there a way to check if a function has completed its operation using either javascript or jquery?
I'm trying to make a counter that slows down as the number gets bigger(decelerating the output, if you will), using setTimeout. As you know, the larger the number the longer the delay (in setTimeout).
What I'm trying to do is click a button, then current loop iteration is printed on the screen. This loop number is used as the setTimeout delay, so while the number is low it will quickly rush through, as it gets bigger the delay is larger thus making it print the number more slowly (since this number is the delay and the larger the delay the less often it prints it).
Here is the logic I'm trying to accomplish
1. Click button
2. Initiate loop
3. trigger function to set timeout
4. set timeout triggers a function to print the loop iteration #
5. Repeat step 3 until the number of set iterations is completed
Well, as you can see when the timeout is set the loop will continue, but there will be a timeout delay. Is there any way that I can put a pause-type function that waits until the timeout function is completed, and then continue onto the next iteration?
Here is my code
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<form>
<input type="button" value="Display alert box"
onclick="setMessage()" />
<script>
function setMessage(){
for(i=0;i<5000;i++){
var b = i;
timeMsg();
//some sort of puase here checking until timeMsg & docWrite are completed, then continue to the next iteration
}
}
function timeMsg(){
var t=setTimeout("docWrite()",b);
}
function docWrite(){
document.write(i);
}
</script>
</form>
</body>
</html>
Instead of doing this in a for loop, I would recommend doing something like the following:
function docWrite(i){
document.write(i);
}
function timeMsg(counter) {
var t;
counter++;
if (counter < 5000) {
t = setTimeout(function(counter){
docWrite(counter);
timeMsg(counter);
}, counter, counter)
}
}
timeMsg(0);
Related
I have an express app running socket.io on my raspberry pi which is controlling an LED panel. To drive the panel I have a while loop that is constantly updating the pixels in the panel. I want to be able to change the parameters of that loop or switch to a different loop altogether to control what animation the panel is displaying.
What is the best way to do this? When I have tried just passing a new socket.io message to the server the message isn't received because it is blocked by the loop. I can start the first animation this way but any subsequent messages are blocked.
I can provide code snippets if needed.
Instead of a loop, use a function that calls itself asynchronously at the end. This allows events like socket.io messages to be handled before the next function execution.
The HTML page below illustrates the idea. The loop increments a counter every second and by pressing the button, you can increase the increment.
<!DOCTYPE html><html>
<head>
<script type="text/javascript">
var counter = 0, increment = 1;
function loop() {
counter += increment;
document.querySelector("span").textContent = counter;
setTimeout(loop, 1000);
}
</script>
</head>
<body onload="loop()">
<span></span>
<button onclick="increment++">Count faster</button>
</body>
</html>
Here, setTimeout(loop) is "sufficiently asynchronous" to allow click events, whereas Promise.resolve().then(loop) would not be. As the comment below says, your code is needed for a judgment how it works for your events.
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
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
I currently have a JavaScript file that will change the testimonial shown every five seconds. Everything works perfectly, except for the first five seconds, nothing appears. If I put a value where the JavaScript function is being called, it does show up initially, then is replaced by whatever the first testimonial is.
Here is the HTML code where the JavaScript is being called.
<html>
<head>
<SCRIPT language="JavaScript" SRC="textCycle.js"></SCRIPT>
</head>
<body>
<table border = 0><tr><td style="width:300px;"> <!-- Change the height in order to determine width of quotes -->
<div id="change"></div></td></tr></table>
</body>
</html>
Here is the Javascript:
var quotes=new Array(5);
var i = 0;
var authors=new Array(5);
//Load Quotes into array
quotes[0]="\"Website is awesome!\"";
quotes[1]="\"Love it!\"";
quotes[2]="\"Awesome site!\"";
quotes[3]="\"This site was very informative and helped with my problem.\"";
quotes[4]="\"Best site for helping with this issue.\"";
//Load authors that correspond with the quote array
authors[0]="Anonymous";
authors[1]="Anonymous";
authors[2]="Anonymous";
authors[3]="Anonymous";
authors[4]="Anonymous";
//Call the changeText() function every 5000 miliseconds
setInterval(changeText, 5000);
//Function that determine what quote and author to put in html.
function changeText(){
document.getElementById("change").innerHTML=(quotes[i] + '<p style="text-align: right"><i>' + authors[i] + '</i></p>');
if(i == 4)
i = 0;
else
i++;
}
Is this just a matter of changing the javascript file so that quotes[0] is outside of the loop?
Note: The values in the arrays were changed to keep it anonymous. These aren't real testimonials.
Just add changeText() (call your function) anywhere in your code before setInterval(). Well, it is not mandatory.
Fiddle
If you add the call to changeText() as mentioned, it likely still will not work. This is because the DOM has not been parsed yet. You should call it after the DOM is ready. One way to do this would be to put it in the onload event. This is the easiest way without a third-party library, but also waits until all images have been loaded. Here is an example:
<body onload="changeText()">
setInterval waits the interval duration (5 seconds) before executing the first time.
You could just call it once before setting the interval, and you'll be good to go. Eg:
//Call the changeText() function every 5000 miliseconds
changeText();
setInterval(changeText, 5000);
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()">