I am trying to run small snippet code in JavaScript, where I want to write on the web page simple hello world each 5 seconds. I think it must be ok, but no, still I got only first hello world and no more. Could you give me a hand in this? Thanks
<script type="text/javascript">
var i=0;
function startTimer() {
window.setTimeout('refresh()',5000);
}
function refresh() {
document.write("Hello world "+i+"<br/>");
i++;
window.setTimeout('startTimer()',1);
}
startTimer();
</script>
NOTE: As Amar Palsapure has noted in this answer, the root cause of the problem was the use of document.write. In my demonstration, I use a p element to document.body.appendChild() to add the text to the screen.
You can use setTimeout(), but you have to make it contingent on the last setTimeout() that ran; so that each time the caller runs, it creates the next timeout.
setInterval() is designed to run at a "regular" interval (neither setTimeout() nor setInterval() are truly reliable in when they run); however, if the calls to setInterval() get backed up due to some other process blocking it's execution (Javascript is single-threaded), you could have issues with those queued callbacks. That's why I prefer the approach I have below.
Note, refrain from the setTimeout('funcCalled()', 100) usage; this is running an eval() on that string you're passing in, which can change the scope in which you're running the callback, as well as being considered "evil" due to security issues related to eval(). You're best to avoid it altogether.
EDIT - Modified slightly.
I have made some changes to the approach. See my comments.
// The first and last lines comprise a self-executing,
// anonymous function, eg, (function(){})();.
// This allows me to use a local function scope and not the
// global window scope, while still maintaining my variables
// due to it being a "closure" (function(){}).
(function(){
var i = 0,
timer = 5000,
// I'm just going to add this to the DOM.
text = document.createElement('p');
// This is a variable function, meaning it stores a
// reference to a function.
var helloWorld = function() {
// Here is where I add the Hello World statement
text.innerHTML += 'Hello World! Loop: ' + i++ + '<br/>';
// Them add it to the DOM.
document.body.appendChild(text);
// I added this so it wouldn't run forever.
if (i < 100) {
// A setTimeout() will be added each time the last
// was run, as long as i < 100.
// Note how I handle the callback, which is the
// first argument in the function call.
setTimeout(helloWorld, timer);
}
// I added the change so it wouldn't take so long
// to see if was working.
timer = 500;
}
// Here I use a variable function and attach it to the
// onload page event, so it will run when the page is
// done loading.
window.onload = helloWorld;
})();
http://jsfiddle.net/tXFrf/2/
The main issue is document.write. There is nothing wrong with setTimeout or rest of the code.
The reason it does not work is that once document.write is called the first time, it overwrites your existing code of setTimeout() and since there is no code so it will not work.
What you need to do is use some other means to write the value in the page, certainly no document.write...
Instead of using setInterval use setTimeout.
You can try this
<html>
<body>
<div id="clock" ></div>
<script type="text/javascript">
var i = 0,
timerHandle,
clock;
function startTimer() {
clock = document.getElementById('clock');
//You can use timerHandle, to stop timer by doing clearInterval(timerHandle)
timerHandle = self.setInterval(funRefresh, 2000);
}
var funRefresh = function refresh() {
clock.innerHTML += "Hello world " + i++ + "<br/>";
}
startTimer();
</script>
</body>
</html>
Hope this helps you.
Here is the working Code
var i = 0;
function startTimer() {
window.setInterval(refresh, 5000);
}
function refresh() {
document.write("Hello world " + i + "<br/>");
i++;
// window.setTimeout(startTimer,1);
}
startTimer();
Related
I am new to javascript, and I am coding a game.
I would like to break out of the setInterval loop when a condition is met to display a game over screen. My code :
var timer = 0;
var i =0;
fond.onload= function()
{
timer = setInterval(boucle,50);
console.log("break");
}
function boucle()
{
i++;
if(i===4)
{
clearInterval(timer);
}
}
I never reach the break log because just after the clearInterval, the screen is stuck.
Thank you!
I am not sure what fond.onload represents in your code, but if you want the code to run when the page is loaded you should use window.onload or document.onload.
onload is a global event handler bound to all objects that gets executed when that object is loaded. I presume that in your case fond is never loaded as the rest of the code is fine, just never runs. It will run fine if you bind the function to window.onload.
You can read up more on that here
I have this code:
window.setTimeout(function() {
let sudokuBodyWidth = $sudokuBody.outerWidth(true);
let sudokuBodyHeight = $sudokuBody.outerHeight(true);
console.log(sudokuBodyWidth + ',' + sudokuBodyHeight);
$sudoku.hide();
$welcomeOverlay.css({
width: sudokuBodyWidth,
height: sudokuBodyHeight
}).show();
}, 800);
window.clearTimeout();
I've put this code in a setTimeout because it takes a lot of time the DOM to load, so the JS code is to early with executing and returns 0 for the values (it's a huge codebase and I'm not 'allowed' to change the site structure to make the JS load later).
The problem is that this code runs twice. First, it returns the correct result, but then it returns 0 for both variables immediately after the correct values. As you can see, I've added a clearTimeout to prevent the execution to happen twice. But it keeps executing twice.
I've also tried:
let welcomeTimeout = setTimeout(function() {
// the code
});
clearTimeout(welcomeTimeout);
When doing this, the code doesn't execute at all.
window.clearTimeout() will do nothing because you are not passing the timerId witch get returned by window.setTimeout() and this should not run twice there is something else witch is causing this function to run twice
and in second one clearTimeout(welcomeTimeout); clears the timer that's why your code doesn't run
if you want to run your code after the document get loaded fully then you can use window.onload = function(){...}
or if you are using jQuery then you can also try $(document).ready(function(){...})
It should execute only once check Ur code base if u r loading script two times mean while put clearTimeout code at the end in the ananymous function given to setTimeout function
Putting the code at the end of HTML executes it when the DOM is loaded.
Use this:
<html>
<head>
<script async src="..."></script>
...
</head>
<body>
...
...
<script>(function() { init(); })();</script>
</body>
</html>
Function init() will fire when the DOM is ready.
Also you're using setTimeout() wrong, take a look at this example.
var what_to_do = function(){ do_stuff(); };
var when_to_do = 3000; // 3000ms is 3 seconds
var timer = setTimeout(what_to_do, when_to_do);
I have just started learning JavaScript, coming from a Java/Clojure background and I am trying to do a simple thread-sleep command that will allow me to have lines of text appear on the screen, at one second intervals. I thought about using the setInterval function instead, but because I am dealing with multiple functions, I thought setTimeout would be better. The problem I am encountering is that all of the text is printing in the browser instantaneously, as though the setTimeout functions weren't even there. Below is an example using the "Happy Birthday" song, which I think succinctly illustrates the problem. How can I make the program below run, line by line, at one second intervals?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Happy Birthday</title>
</head>
<body>
<script>
var name = "Joe",
i = 0;
while (i < 2) {
setTimeout(document.write("Happy Birthday to you!<br>"), 1000);
i ++;
}
setTimeout(document.write("Happy Birthday dear " + name + ",<br>"), 1000);
setTimeout(document.write("Happy Birthday to you!<br>"), 1000);
</script>
</body>
</html>
To delay evaluation of some code, this code should be put into a function; that function reference should be passed into setTimeout. For example:
setTimeout(function() {
document.write('Hello world!');
}, 1000);
As it stands, you evaluate document.write expression instead immediately - that's why you see all the writings occurring simultaneously.
As a sidenote, please please please don't use document.write unless you're really know what're you're doing. It's quite easy to 'log' something just by adjusting innerHTML of log element. For example:
<div id="log"></div>
<script>
var log = document.getElementById('log');
setTimeout(function() {
log.innerHTML += 'Hello world!<br />';
}, 1000);
</script>
Also, don't forget that each timeout is processed independently. To set up a chain of events, you'd manually increase the delay - otherwise all the functions will be called almost immediately after each other.
Overall, here's how it can be done:
<div id="log"></div>
<script>
var name = "Joe",
i = 0,
delayedMessage = function(msg) {
setTimeout(function() {
document.getElementById('log').innerHTML += msg;
}, ++i * 1000);
};
delayedMessage("Happy Birthday to you!<br>");
delayedMessage("Happy Birthday to you!<br>");
delayedMessage("Happy Birthday dear " + name + ",<br>");
delayedMessage("Happy Birthday to you!<br>");
</script>
Demo.
In your code you were executing the document.write and then setting the timeout handler with its return value which is clearly wrong.
Remember you must always pass a function (a handler) to every event you want to react to.
So, the correct code is:
setTimeout(function(){
document.write("Happy Birthday to you!<br>");
}, 1000);
I want to refresh a span element before my calculations start to inform user that calculation was started.
the following code never displays 'calculating' message:
<script>
document.getElementById('text').innerHTML = 'calculating';
for (var i=0; i<9999;i++){
var y = Math.pow(i,i);
console.log(y);
}
document.getElementById('text').innerHTML = 'done';
</script>
</body>
</html>
how to fix that?
Guys, setTimeout is not an option for me. besides it looks ugly.
Place your code inside a setTimeout() call, and add a very minimal delay. I usually put 0ms, which just waits for the frame to render, then calls the function. Example:
document.getElementById('text').innerHTML = 'calculating';
setTimeout(function() {
for (var i=0; i<9999;i++){
var y = Math.pow(i,i);
console.log(y);
}
document.getElementById('text').innerHTML = 'done';
}, 0);
The first argument is a function to be called after the time passes, the second argument is the time to wait before calling the function. Note that this may still hang the browser if the calculation is too big (e.g. 999999 loop steps on a 2.5GHz i5)
i got a problem with setTimeout.. i dont know why this will not work..
$(document).ready(function(){
var counterNum = 0;
function tick()
{
addText(counterNum);
setTimeout('tick()',1000);
counterNum++;
}
function addText(strNum)
{
$("div.counter").empty();
$("div.counter").append(strNum);
}
});
you can check it here for the live preview LINK
and also sir, what is the difference between
setTimeout('tick()',1000);
and
setTimeout(tick(),1000);
?
Try:
$(document).ready(function(){
var counterNum = 0;
function tick()
{
addText(counterNum);
setTimeout(tick,1000);
counterNum++;
}
function addText(strNum)
{
$("div.counter").empty();
$("div.counter").append(strNum+"");
}
tick();
});
The difference between
setTimeout('tick()',1000)
and
setTimeout(tick(), 1000)
is that the second one will not wait 1000ms to execute, but if you changed it to
setTimeout(tick, 1000)
it would be effectively the same. Technically, it would change the scope of where the function was called from.
In the case of passing in a string JavaScript has to evaluate it to run your code. With setTimeOut you should always use a pattern like this:
var self = this;
setTimeout(function(){tick();},1000);
This gives you closure and allows you to get around the fact that using setTimeOut changes what this is to be the global object window (a nastly little surprise for developers the first time they encounter it).
Try that in combination with Fredrik recommendeds and you should be in good shape.