difference between setTimeout() and setInterval() [duplicate] - javascript

This question already has answers here:
setTimeout or setInterval?
(20 answers)
'setInterval' vs 'setTimeout' [duplicate]
(5 answers)
Closed 8 years ago.
i am trying to move a small div along a big div in the y-direction according to how much i scrolled down the page.but i've found that using setTimeout() and setInterval() gives two completely different results.actually setInterval() hanged by browser several times .what is the basic difference between the two function??
<!DOCTYPE html>
<head>
<title>creat a dynamic div</title>
<style>
#mydiv{
border:2px solid green;
}
</style>
</head>
<body>
<script>
var i=0;
var elem1=document.createElement("div");
var atts1=document.createAttribute("style");
atts1.value="width:200px;height:3200px;border:1px solid black;background-color:orange;";
elem1.setAttributeNode(atts1);
document.body.appendChild(elem1);
var elem2=document.createElement("div");
var atts2=document.createAttribute("style");
var atts22=document.createAttribute("id");
atts22.value="mydiv";
atts2.value="width:200px;height:300px;background-color:red;position:absolute;top:0px;left:300px;";
elem2.setAttributeNode(atts2);
elem2.setAttributeNode(atts22);
document.body.appendChild(elem2);
function moveIt(){
var a=window.pageYOffset;
if(i > (a+30)){
clearTimeout(p);
}else{
elem2.style.top=i+"px";
i=i+1;
}
var p=setTimeout(moveIt,200);
}
window.onscroll=moveIt;
</script>
</body>
<html>

setTimeout executes the function once on a time out. setInterval executes the function repeatedly on and interval
https://developer.mozilla.org/en-US/docs/Web/API/Window.setTimeout
https://developer.mozilla.org/en-US/docs/Web/API/Window.setInterval

setTimeout will only execute the function once whereas setInterval will execute the function every n seconds (whatever you specify).

Related

JavaScript doesn't run when tab isn't open [duplicate]

This question already has answers here:
How can I make setInterval also work when a tab is inactive in Chrome?
(16 answers)
Chrome: timeouts/interval suspended in background tabs?
(7 answers)
Closed 4 years ago.
For some reason, my code doesn't appear to run in the background if the tab's not open.
Here is the code:
num = 0;
window.setInterval(function() {
num = num + 1;
document.getElementById('num').innerHTML = num;
}, 10);
<html>
<head>
<title>Space...</title>
</head>
<body>
<span id="num">0</span>
<script src="main.js"></script>
</body>
But it is working on a separate game I've made, i.e. it does continue running if the tab's not open.
I've searched the web and Stack Overflow for answers, but I haven't been able to find any. I don't know why this is happening, so any help would be much appreciated. Thanks in advance!

How to call ajax while scrolling inner scroll of div [duplicate]

This question already has answers here:
jQuery : how to determine that a div is scrolled down
(7 answers)
Closed 9 years ago.
I want to call ajax function while scrolling inner scroll and append the results at the bottom of the existing results.
For refrence I've attached an image here.
How can I achive this?
You can use something like this without jQuery also
window.onload = function(){
if(window.addEventListener){
document.addEventListener('DOMMouseScroll', moveObject, false);
}
var myDiv = document.getElementById("myDiv");
myDiv.onmousewheel = ajaxFunction();
}

Javascript code not working? Tell me why [duplicate]

This question already has answers here:
Setting innerHTML: Why won't it update the DOM?
(7 answers)
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 10 years ago.
I was working on a simple javascript code and I don't know what it is not working.
Please tell me if you figure this out.
<!DOCTYPE html>
<html>
<head>
<script>
function displayText(){
var xa = document.getElementById('abcd').innerHTML;
xa+= 'asdf';
}
displayText();
</script>
</head>
<body>
<div id="abcd"></div>
</body>
</html>
innerHTML returns a String of the current contents of the element and not a pointer to it. So use this instead:
function displayText(){
document.getElementById('abcd').innerHTML += 'asdf';
}
or
function displayText(){
var el = document.getElementById('abcd');
var xa = el.innerHTML;
xa += 'asdf';
el.innerHTML = xa;
}
Furthermore you can not call the function, before the element you are referring to is actually created. So move the call at the bottom of the body tag.
<!-- .... -->
<script>
display();
</script>
</body>
At the time the code runs the body (including your div) has not yet been parsed. getElementById('abcd') doesn't find anything at that time.
Either move your script element to the end of the body so that it runs after the body has been parsed, or call your displayText() function from an onload handler.
(And if you intend the new value in xa to be displayed in the same field you'll need to write it back to the element with document.getElementById('abcd').innerHTML = xa.)

JavaScript Change Text in X Seconds - No Initial Display

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

pause until event/function is completed with jquery or javascript

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

Categories