How do I use javascript setTimout? - javascript

I have a small piece of javascript that I would like to use but need a delay before it's activated.
function sglClick(url) {
window.setTimeout('location.href="http://'"+url",1500);
}
This is not working and I'm really stuck here.
Here is what I now have
function send(){
}
function sglClick(url) {
// window.location.href="http://"+url;
setTimeout(function send() { location.href = "http://" + url; },1500);
}

try this
function sglClick(url) {
setTimeout(function() { location.href = "http://" + url; },1500);
}
This is using an anonymous function to house your code. It should take approx 1.5 seconds to fire. I say approx because JavaScript is single threaded, and other function calls/etc can actually make the interval fire at a slightly different time (but 9/10 this is a non-issue)
It is also assuming you're sending things like this to the function
sglClick('www.google.com');
As your code is prefixing the argument with http://
I've always used this function as just simply setTimeout(), not as a method of the window object.

Related

How can I automatically change a page in Javascript?

Trying to get the code to automatically change page using setTimeout, but I do not get it to work.
setTimeout()(page3, 500);
function page3() {
changepage3('automatic')
}
This is what my code looks like right now, but I am suspecting that this is not enough. Anyone knows what is missing?
try this one
function page3() {
changepage3('automatic')
}
setTimeout(page3, 500);
setTimout needs a specific syntax to work, check it out on the best JavaScript documentation by Mozilla: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Syntax
Here is an example
saySomethingAfter(5);
function saySomethingAfter(second) {
setTimeout(saySomething, second * 1000);
}
function saySomething() {
console.log("Something");
}
Your question is "How can I automatically change a page in Javascript?" using setTimeout. Let's analyse the needs:
change a page → open a new URL (cf. Open URL in same window and in same tab)
automatically using setTimeout → with the correct syntax
function changePage(url) {
window.open(url, "_self");
}
function changePageAfter5sec(url) {
setTimeout(function() {
changePage(url)
}, 5000);
}
changePageAfter5sec("https://stackoverflow.com")
Another way using beautiful functional JavaScript:
function changePage(url) {
return () => {
window.open(url, "_self");
}
}
function changePageAfter(second) {
return (url) => {
setTimeout(changePage(url), second*1000);
}
}
const changePageAfter5sec = changePageAfter(5);
changePageAfter5sec("https://stackoverflow.com")
You have 2 major problems in the code snippet provided:
That is not correct setTimeout() syntax - thus it doesn't actually work.
Even if it did work, it would call 1 function that uses another function which doesn't exist thus breaking the code.
fix problem number 1:
window.setTimeout(changePage, 5000);
now we have a running timeout that will trigger 5000 milliseconds after initiation(usually).
so let's fix problem 2 and let changepage() call an actual proper url opening function:
function changePage(){
window.open(urlOfPage3);
}
Finally a simpler version with an anonymous callback function in the setTimeout:
window.setTimeout(function(){
window.open(urlOfPage3);
}, 5000);

How to use Ajax to populate externally loaded div (jQuery)

I am creating tests for a page and HAVE to use jQuery to change elements on the control version of the page for each different experience.
I'm using jquery to load an element from an external page and replace a div. However, on the external page, it uses an ajax call to an api to populate the div, so I copied over the function with the ajax call.
I think it is attempting to make the ajax call before the new div is actually loaded on the page.
I've tried moving the function, wrapping the load function within the ajax call, but it still doesnt work.
I could be missing something obvious, but here's that part of my code:
$('.replace-div').load('external.html #replace-div');
function waitForLoad() {
if ($('#replace-div')) {
var object;
$.ajax({
url: "https://api.com",
async: false,
success: function(result) {
object = result;
var variable1 = object["blah"][0].value,
var variable2 = object["blah"][0].value,
var variable3 = object["blah"][0].value,
var variable4 = object["blah"][0].value,
$('newElement').attr('href', variable1);
$('newElement2').attr('src', variable2);
$('newElement3').attr('href', variable3);
$('newElement4').text("text" + variable4 + "more text");
}
});
} else {
setTimeout(waitForLoad, 15);
}
}
waitForLoad();
I don't get any errors in the console, and when I paste the above waitForLoad function into the console, it populates totally fine. obviously this is after the page loads the new div, so i just need to know how to make the ajax call wait for the load.
I've tried .ajaxComplete(), but it doesnt help.
$(function() {}); also does not work
.load() has a callback argument where you supply a function to run after the data is loaded.
$('replace-div').load('external.html #replace-div', function() {
$.ajax(...);
});
So, what happens is that, once waitForLoad is called for the first time, it doesn't see the div loaded, the code goes to the else block and executes again with a 15ms timeout. 15ms is not enough for the div to load, most likely.
You can try three things (ordered from worse to better):
Try increasing the timeout to a bigger number. Start with 1000 (1000ms - 1 second) and see if it works or you need to increase it. It's more likely you'll have to decrease it
Try using setInterval instead of setTimeout, which will repeat itself. Of course, once it loads, you'll need to clear the interval so it stops. Also, better use bigger timeouts/intervals, like 50 or 100ms b/c the fast firing timers can slow down a page a lot
E.g.
$('.replace-div').load('external.html #replace-div');
function waitForLoad() {
if ($('#replace-div')) {
clearInterval(window.waiter);
...
} else {
window.timer = setInterval(waitForLoad, 50);
}
}
waitForLoad();
Same as 2, but using more idiomatic callback function after load call.
// the window.waiter is the interval handle, and it will run every 100ms. It calls .load every time, and if the #replace-div is found, unsets the interval handle.
window.waiter = setInterval(function() {
$(".replace-div").load("external.html #replace-div", function() {
if ($(".replace-div #replace-div").length) {
// found the DIV
// code...
clearInterval(window.waiter); // bye interval handle, thanks
}
});
}, 100);

Adding text periodically

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

setTimeout Problem

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.

javascript setTimeout function out of scope

I am trying to call showUpload(); from within two setTimeouts. Neither works. It seems to be out of scope and I'm not sure why. I tried this.showUpload() which didn't work either.
$(document).ready(function(){
var progress_key = $('#progress_key').val();
// this sets up the progress bar
$('#uploadform').submit(function() {
setTimeout("showUpload()",1500);
$("#progressbar").progressbar({ value:0}).fadeIn();
});
// uses ajax to poll the uploadprogress.php page with the id
// deserializes the json string, and computes the percentage (integer)
// update the jQuery progress bar
// sets a timer for the next poll in 750ms
function showUpload() {
$.get("/myid/videos/uploadprogress/" + progress_key, function(data) {
if (!data)
return;
var response;
eval ("response = " + data);
if (!response)
return;
var percentage = Math.floor(100 * parseInt(response['bytes_uploaded']) / parseInt(response['bytes_total']));
$("#progressbar").progressbar({ value:percentage})
});
setTimeout("showUpload()", 750);
}
});
Thank you for your time.
As #Daniel said, this should work:
setTimeout(showUpload, 750);
Please note that the quotes should be removed (this is why it isn't being executed until the timeout runs out). Right now, you are passing a string, which is evaled when the timeout runs out. This eval will happen in a different scope, which is why you are seeing the problem you are seeing.
Instead, passing a reference to the showUpload function to setTimeout will allow your function to be executed later. Keep in mind that when it runs, it will be in a different scope, so you may have other scope issues, like with progress_key. You will need to create a closure around showUpload to capture that parameter.
It looks like you need to remove the parenthesis from showUpload in both your setTimeout calls. Otherwise you will be invoking the showUpload method instead of passing it as a parameter:
setTimeout(showUpload, 750);

Categories

Resources