Javascript to jQuery for loading page please wait [duplicate] - javascript

Firefox always loads dynamic images, but IE it just shows images without any dynamic action. what changes I need to do?
JavaScript code from IE view source code:
<script type=”text/javascript”
<!--/*--><![CDATA[/*><!--*/
if (document.getElementById("safeForm1d3").submitted.value == "false") {
document.getElementById("safeForm1d3").submitted.value = "true";
setTimeout('document.getElementById("safeForm1d3").submit()', 100);
}else{
document.getElementById("toHide").style.display="none";
}/*-->]]>*/
</script>
I am using Wicket framework, so real java code is:
static private class SafeSubmitBehaviour extends AbstractBehavior{
public void onRendered( Component component ) {
super.onRendered( component );
StringBuffer buffer = new StringBuffer(200);
buffer.append("<script type=\"text/javascript\" ><!--/*--><![CDATA[/*><!--*/\n");
buffer.append("if (document.getElementById(\"").append(component.getMarkupId()).append("\").submitted.value == \"false\") {\n");
buffer.append("document.getElementById(\"").append(component.getMarkupId()).append("\").submitted.value = \"true\";\n");
buffer.append("setTimeout('document.getElementById(\"").append(component.getMarkupId()).append("\").submit()', 100);\n}else{\n");
buffer.append("document.getElementById(\"toHide\").style.display=\"none\";\n}/*-->]]>*/</script>");
component.getResponse().write(buffer);
}
}
html page which loads my dynamic image is:
<div id="toHide" class="pb-text-align-center">
<img style="display: inline" src="img/load.gif" />
<form wicket:id="safeForm" class="clearfix">
<input type="hidden" wicket:id="submitted" value="false" />
</form>
</div>

Because setTimeout() requires your function to be passed as a string or as an anonymous function:
setTimeout(function() { document.getElementById("safeFormec").submit(); }, 100);

Take away the quotes from around your action:
setTimeout(function() {
document.getElementById("safeForm4d").submit();
}, 3000);

Have you tried removing the function call brackets from the end of this line?
document.getElementById("safeForm9c").submit()
i.e. do this instead:
setTimeout(document.getElementById("safeForm9c").submit, 100)
You’re telling IE to call the results of submit() in 100 milliseconds time, rather than call submit.

Try wrapping them inside a function:
setTimeout(function(){ document.getElementById("safeForm4d").submit(); }, 100);

Try something like this
setTimeout(function(){document.getElementById("safeForm9c").submit();}, 100);
In the old days a setTimeout complete function was in a string format, but these days we use it this way. Also this way makes is possible to do more things when the timeout is complete.

function setsubmit()
{
document.getElementById("safeFormec").submit();
}
setTimeout('setsubmit()',100);

change this
setTimeout(function() {
'document.getElementById("safeForm4d").submit()'
}, 3000);
to...
setTimeout(function() {
document.getElementById("safeForm4d").submit()
}, 3000);

Can you try doing something like
setTimeout('document.getElementById("safeForm9c").submit()', 100);
Probably setTimeout accepts the things you want to call as a string, so that it can do an eval after the timeout and run the script as it encouters in the string.

Include this in the head
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
and have
static private class SafeSubmitBehaviour extends AbstractBehavior{
public void onRendered( Component component ) {
super.onRendered( component );
StringBuffer buffer = new StringBuffer(200);
buffer.append("<script type=\"text/javascript\" >\n");
buffer.append("var input = $(\"input[name='submitted']\");\n");
buffer.append("if (input.val() == \"false\") {\n");
buffer.append(" input.val(\"true\");\n");
buffer.append(" setTimeout(function(){ $(\"#").append(component.getMarkupId()).append("\").submit()}, 100);\n");
buffer.append("}\n");
buffer.append("else {\n $(\"#toHide\").hide();\n}");
component.getResponse().write(buffer);
}
}
which should render
var input = $("input[name='submitted']");
if (input.val() == "false") {
input.val("true");
setTimeout(function(){ $("#safeForm1d3").submit()}, 100);
}else{
$("#toHide").hide();
}
Where would you do the $("#toHide").show(); ?

solved my problem. may be useful for others:
Answer:
HTML source code:
<SCRIPT type="text/javascript">
var $ = jQuery.noConflict();
document.getElementById('toHide').style.display ="";
$('#toHide').doTimeout(1000, function() {
$('#toHide').find('#safeForm34').submit();
document.getElementById('myAnimatedImage').src = "../../img/load.gif";
});
</SCRIPT>
html:
<div id="toHide" class="pb-text-align-center">
<img src="img/load.gif" id='myAnimatedImage' style="margin-left: auto; margin-right: auto;"/>
<form wicket:id="safeForm" class="clearfix" />
</div>

You can try:
img style="display: inline" src="img/load.gif?salt=xxxx"
xxx: means - a random of an integer.
Maybe, the browser cache the image so it will not repaint. Or you must set the GIF image with loop.

I have tried with adding function call, now images are loading and dynamic, but it never goes to next page or never clear timeout.
code:
buffer.append("setTimeout(function(){'document.getElementById(\"").append(component.getMarkupId()).append("\").submit()'}, 100);\n}else{\n");

var safeForm4d = document.getElementById("safeForm4d");
if ( safeForm4d.submitted.value == "false" ){
safeForm4d.submitted.value = "true";
setTimeout(function(){ safeForm4d.submit(); }, 100);
}else{
document.getElementById("toHide").style.display="none";
}

This:
setTimeout(function(){'document.getElementById("safeForm4d").submit()'}, 100);
is incorrect. The function you pass there to ".setTimeout()" will do nothing. Instead of that, try:
setTimeout(function(){ document.getElementById("safeForm4d").submit(); }, 100);
The difference is that the actual guts of the function should not have been quoted. In that state, what you've got is a function with a single statement, that statement being a simple string-valued expression. It would run, but have no effect.

two things:
The correct usage of setTiemout() is:
setTimeout(function(){
document.getElementById("safeForm4d").submit();
}, 100);
Your using wicket. The wicket:id is nothing the DOM knows. You have to assign an ID and use this one like you did it with the form itself.
Hope that helps.

setTimeout(function (){ document.getElementById("safeForm").submit() } , 100);
check working example at JSFIDDLE.
CAUTION:: alert may be irritating.

The setTimeout function throws invalid arguments because whatever the call
document.getElementById("safeFormec").submit()
returns (some error message maybe) is not a valid argument to setTimeout i.e. it can not
be resolved to a function or expression.
The call to .submit() fails because there is no action attribute specified for the form (<form action="somePage.php">).
Your intention was probably not to do a submit in the setTimeout call, but to send the submit function as a value parameter to setTimeout to be executed after a while. Like this:
setTimeout(document.getElementById("safeFormec").submit, 100);
Note the missing paranthesises.

Issue was with time 100 ie 1/10 of second. IE will load images with dynamic action only for for 100 millisecond ie1/10 second and stop. increased time to 3000 and now it is working fine.
setTimeout(function(){'document.getElementById("safeForm4d").submit()'},
100);
No issues with FF or other browser.

After formatting your initial post I think maybe I found some sources to the problem.
The function in your timeout is a string.
You should try and submit the form, not the actual button.
Try this:
if (!document.getElementById("safeForm4d").submitted.value) {
document.getElementById("safeForm4d").submitted.value = "true";
setTimeout(function() {
document.forms[0].submit(); // Alt: document.forms['MyFormName'].submit()
}, 3000);
} else {
document.getElementById("toHide").style.display="none";
}

This will never give you the desired effect because your changing from page to page -- this will cause the aninmation to disappear once the new page starts to load. This will depend on many factors, such as how long the server takes to response, to how fast the user's computer is to re-render the new page.
If you really want this kind of effect to work you should use ajax to send the form data using .serialize(), overwrite the current page with the response which should hide the animation.
Update:
To create the desired effect you'll have to post the form using ajax, then push the new HTML to the DOM.
var $form = $('#formId');
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: $form.serialize(),
success: function(response) {
$('#loading').fadeOut(function() {
// Get only text from the body of the result
$('body').html($(response).find('body'));
});
}
});
This is really hacky though and I felt dirty writing that. Seriously. You should really make sure that the response returned isn't go to:
Reload CSS styles, scripts, etc.
Any specific title, scripts, styles, etc relevant to that page and search will not appear or be changed.
More than likely you just want to return the result to the query i.e. the search results of the form submitted. In which case just wrap the results in a container and .find('#container') instead of .find('body')

Try this:
<script type="text/javascript">
if (document.getElementById("safeForm4d").submitted.value == "false") {
document.getElementById("safeForm4d").submitted.value = "true";
setTimeout('document.getElementById("safeForm4d").submit()', 100);
} else {
document.getElementById("toHide").style.display="none";
}
</script>

You have quotes in the setTimeout event:
setTimeout('document.getElementById("safeForm4d").submit()', 100);
Change your script as follows:
<script type="text/javascript">
if (document.getElementById("safeForm4d").submitted.value == "false") {
document.getElementById("safeForm4d").submitted.value = "true";
if(Wicket.Browser.isIE()) {
setTimeout(document.getElementById("safeForm4d").submit(), 100);
} else {
setTimeout(document.getElementById("safeForm4d").submit(), 100);
}
} else {
document.getElementById("toHide").style.display="none";
}
</script>

Finally solved my question, may be useful for others:
Answer:
HTML source code:
<SCRIPT type="text/javascript">
var $ = jQuery.noConflict();
document.getElementById('toHide').style.display ="";
$('#toHide').doTimeout(1000, function() {
$('#toHide').find('#safeForm34').submit();
document.getElementById('myAnimatedImage').src = "../../img/load.gif";
});
</SCRIPT>
html:
<div id="toHide" class="pb-text-align-center">
<img src="img/load.gif" id='myAnimatedImage' style="margin-left: auto; margin-right: auto;"/>
<form wicket:id="safeForm" class="clearfix" />
</div>

Related

How to refresh a script after some time using Javascript

There is a variable I want to update every minute.
So am curious whether there is a way in Javascript where I can refresh the whole script after some time instead of the variable itself.
<script>
function vName(){
videos = $('#videos').text();
}
vName();
Use setInterval. Here hello will print each and every 3sec
setInterval(function(){ console.log("Hello"); }, 3000);
You could achive this using an event to listen to the element's change:
(function () {
"use strict";
let videos = '';
$("#videos").on("change", evt => {
videos = $(evt.target).val();
console.log(videos);
});
})();
body {
margin: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="videos" type="text">
Solution
Set interval is a function which is being used to perform any functionality after a specific desired time span . The function is always called again and again after that time period . The below code is an example for setInterval.
Code:-
setInterval(function(){ alert("Video is here "); }, 9000);
Explanation
you can call any method in place of "alert("Video is here")" and the desired time period is being given in place of "9000" that means the specific function is being called after every 9 seconds
You can put your code in setInterval() function, like this
setInterval(()=>{
//your script here
function vName(){
videos = $('#videos').text();
}
vName();
}, 60000);

Accessing function from within another with Javascript

I'm trying to get the jquery loadmask addon to work that will mask elements (for loading content). I'm using knockout.js, and when if I mask an element outside of my viewmodel it works, but I want to mask it upon submitting a POST request, and then unmask when I receive it. I'm getting an "object has no method mask" error from this. I'm not quite sure how to go about setting up an object to access it.
This works, but it's not what I want. I noted in the code where I would like to call mask from
<div id = "register_container">
<div data-bind="visible: register()">
<div id = "register_form"> <!--this is the div I want to mask -->>
<button data-bind="click: submitRegistration">Submit</button>
</div>
</div>
</div>
function MyViewModel(){
self.submitRegistration = function(){
//I want to mask here. When I try it says Object[object object] has no method mask
$.post....{
if(data.result == success){
// andunmask here
}
}
}
}
$("#register_form").mask("Waiting..."); //the masking works when I place it here, but it's always enabled and I want it inside the viewmodel where I noted so it only works when the POST request is in process
That's great and all, but I want to mask something from inside the viewmodel where I noted. How can I accomplish this?
I see several things that could be the problem.
Frist, you're doing assignment as opposed to comparison in the if statement. Use this instead:
if(data.result == success){
or even
if(data.result === success){
Second is the fact that I don't quite understand your code self.submitRegistration(){, which typically looks more like this:
var MyViewModel = function () {
var self = this;
self.submitRegistration = function() {
};
};
Then, if I mock the $.post call, it would work like this:
var MyViewModel = function () {
var self = this;
self.register = ko.observable(true);
self.submitRegistration = function() {
$("#register_form").mask("Waiting...");
// Mock $.post
window.setTimeout(function () {
if (1 == 1) {
// andunmask here
$("#register_form").unmask();
}
}, 3000);
}
};
ko.applyBindings(new MyViewModel());
See this fiddle for a demo.
You could even have Knockout help you find the element to look for:
See this updated fiddle for a demo of that.
// Use the "event" parameter to find the element...
self.submitRegistration = function(data, event) {
$(event.target).closest('#register_form').mask("Waiting...");
Hope it helps.

problems with jquery load()

I need a certain div refreshed on the page every 3 seconds. This div contains other divs inside it.
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
setInterval(function()
{
$('#gamewrapper2').load('find.php #gamewrapper2');
}, 3000);
;
This code works but only if the page visited is domain/find.php and it doesn't work for domain/find.php?id=1000001
Maybe i don't understand something but shouldn't this function load take the block #gamewrapper2 from find.php and paste it into the block #gamewrapper2 of the current page?
Do you just need to keep the query string on find.php? Something like:
setInterval(function(){
$('#gamewrapper2').load(window.location.pathname + window.location.search + ' #gamewrapper2');
}, 3000);
You can try the following to pass variables into the php document:
setInterval(function()
{
$('#gamewrapper2').load('find.php #gamewrapper2', {id: 1000001});
}, 3000);
}
Additionally, you can provide a function callback when it has completed loading to perform some task...
setInterval(function()
{
$('#gamewrapper2').load('find.php #gamewrapper2', {id: 1000001}, function(){
alert("find.php has been loaded.");
});
}, 3000);
}
.load() method
You should probably use $_POST['id'] to get the value from find.php.

dynamic images are not loading in IE [duplicate]

Firefox always loads dynamic images, but IE it just shows images without any dynamic action. what changes I need to do?
JavaScript code from IE view source code:
<script type=”text/javascript”
<!--/*--><![CDATA[/*><!--*/
if (document.getElementById("safeForm1d3").submitted.value == "false") {
document.getElementById("safeForm1d3").submitted.value = "true";
setTimeout('document.getElementById("safeForm1d3").submit()', 100);
}else{
document.getElementById("toHide").style.display="none";
}/*-->]]>*/
</script>
I am using Wicket framework, so real java code is:
static private class SafeSubmitBehaviour extends AbstractBehavior{
public void onRendered( Component component ) {
super.onRendered( component );
StringBuffer buffer = new StringBuffer(200);
buffer.append("<script type=\"text/javascript\" ><!--/*--><![CDATA[/*><!--*/\n");
buffer.append("if (document.getElementById(\"").append(component.getMarkupId()).append("\").submitted.value == \"false\") {\n");
buffer.append("document.getElementById(\"").append(component.getMarkupId()).append("\").submitted.value = \"true\";\n");
buffer.append("setTimeout('document.getElementById(\"").append(component.getMarkupId()).append("\").submit()', 100);\n}else{\n");
buffer.append("document.getElementById(\"toHide\").style.display=\"none\";\n}/*-->]]>*/</script>");
component.getResponse().write(buffer);
}
}
html page which loads my dynamic image is:
<div id="toHide" class="pb-text-align-center">
<img style="display: inline" src="img/load.gif" />
<form wicket:id="safeForm" class="clearfix">
<input type="hidden" wicket:id="submitted" value="false" />
</form>
</div>
Because setTimeout() requires your function to be passed as a string or as an anonymous function:
setTimeout(function() { document.getElementById("safeFormec").submit(); }, 100);
Take away the quotes from around your action:
setTimeout(function() {
document.getElementById("safeForm4d").submit();
}, 3000);
Have you tried removing the function call brackets from the end of this line?
document.getElementById("safeForm9c").submit()
i.e. do this instead:
setTimeout(document.getElementById("safeForm9c").submit, 100)
You’re telling IE to call the results of submit() in 100 milliseconds time, rather than call submit.
Try wrapping them inside a function:
setTimeout(function(){ document.getElementById("safeForm4d").submit(); }, 100);
Try something like this
setTimeout(function(){document.getElementById("safeForm9c").submit();}, 100);
In the old days a setTimeout complete function was in a string format, but these days we use it this way. Also this way makes is possible to do more things when the timeout is complete.
function setsubmit()
{
document.getElementById("safeFormec").submit();
}
setTimeout('setsubmit()',100);
change this
setTimeout(function() {
'document.getElementById("safeForm4d").submit()'
}, 3000);
to...
setTimeout(function() {
document.getElementById("safeForm4d").submit()
}, 3000);
Can you try doing something like
setTimeout('document.getElementById("safeForm9c").submit()', 100);
Probably setTimeout accepts the things you want to call as a string, so that it can do an eval after the timeout and run the script as it encouters in the string.
Include this in the head
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
and have
static private class SafeSubmitBehaviour extends AbstractBehavior{
public void onRendered( Component component ) {
super.onRendered( component );
StringBuffer buffer = new StringBuffer(200);
buffer.append("<script type=\"text/javascript\" >\n");
buffer.append("var input = $(\"input[name='submitted']\");\n");
buffer.append("if (input.val() == \"false\") {\n");
buffer.append(" input.val(\"true\");\n");
buffer.append(" setTimeout(function(){ $(\"#").append(component.getMarkupId()).append("\").submit()}, 100);\n");
buffer.append("}\n");
buffer.append("else {\n $(\"#toHide\").hide();\n}");
component.getResponse().write(buffer);
}
}
which should render
var input = $("input[name='submitted']");
if (input.val() == "false") {
input.val("true");
setTimeout(function(){ $("#safeForm1d3").submit()}, 100);
}else{
$("#toHide").hide();
}
Where would you do the $("#toHide").show(); ?
solved my problem. may be useful for others:
Answer:
HTML source code:
<SCRIPT type="text/javascript">
var $ = jQuery.noConflict();
document.getElementById('toHide').style.display ="";
$('#toHide').doTimeout(1000, function() {
$('#toHide').find('#safeForm34').submit();
document.getElementById('myAnimatedImage').src = "../../img/load.gif";
});
</SCRIPT>
html:
<div id="toHide" class="pb-text-align-center">
<img src="img/load.gif" id='myAnimatedImage' style="margin-left: auto; margin-right: auto;"/>
<form wicket:id="safeForm" class="clearfix" />
</div>
You can try:
img style="display: inline" src="img/load.gif?salt=xxxx"
xxx: means - a random of an integer.
Maybe, the browser cache the image so it will not repaint. Or you must set the GIF image with loop.
I have tried with adding function call, now images are loading and dynamic, but it never goes to next page or never clear timeout.
code:
buffer.append("setTimeout(function(){'document.getElementById(\"").append(component.getMarkupId()).append("\").submit()'}, 100);\n}else{\n");
var safeForm4d = document.getElementById("safeForm4d");
if ( safeForm4d.submitted.value == "false" ){
safeForm4d.submitted.value = "true";
setTimeout(function(){ safeForm4d.submit(); }, 100);
}else{
document.getElementById("toHide").style.display="none";
}
This:
setTimeout(function(){'document.getElementById("safeForm4d").submit()'}, 100);
is incorrect. The function you pass there to ".setTimeout()" will do nothing. Instead of that, try:
setTimeout(function(){ document.getElementById("safeForm4d").submit(); }, 100);
The difference is that the actual guts of the function should not have been quoted. In that state, what you've got is a function with a single statement, that statement being a simple string-valued expression. It would run, but have no effect.
two things:
The correct usage of setTiemout() is:
setTimeout(function(){
document.getElementById("safeForm4d").submit();
}, 100);
Your using wicket. The wicket:id is nothing the DOM knows. You have to assign an ID and use this one like you did it with the form itself.
Hope that helps.
setTimeout(function (){ document.getElementById("safeForm").submit() } , 100);
check working example at JSFIDDLE.
CAUTION:: alert may be irritating.
The setTimeout function throws invalid arguments because whatever the call
document.getElementById("safeFormec").submit()
returns (some error message maybe) is not a valid argument to setTimeout i.e. it can not
be resolved to a function or expression.
The call to .submit() fails because there is no action attribute specified for the form (<form action="somePage.php">).
Your intention was probably not to do a submit in the setTimeout call, but to send the submit function as a value parameter to setTimeout to be executed after a while. Like this:
setTimeout(document.getElementById("safeFormec").submit, 100);
Note the missing paranthesises.
Issue was with time 100 ie 1/10 of second. IE will load images with dynamic action only for for 100 millisecond ie1/10 second and stop. increased time to 3000 and now it is working fine.
setTimeout(function(){'document.getElementById("safeForm4d").submit()'},
100);
No issues with FF or other browser.
After formatting your initial post I think maybe I found some sources to the problem.
The function in your timeout is a string.
You should try and submit the form, not the actual button.
Try this:
if (!document.getElementById("safeForm4d").submitted.value) {
document.getElementById("safeForm4d").submitted.value = "true";
setTimeout(function() {
document.forms[0].submit(); // Alt: document.forms['MyFormName'].submit()
}, 3000);
} else {
document.getElementById("toHide").style.display="none";
}
This will never give you the desired effect because your changing from page to page -- this will cause the aninmation to disappear once the new page starts to load. This will depend on many factors, such as how long the server takes to response, to how fast the user's computer is to re-render the new page.
If you really want this kind of effect to work you should use ajax to send the form data using .serialize(), overwrite the current page with the response which should hide the animation.
Update:
To create the desired effect you'll have to post the form using ajax, then push the new HTML to the DOM.
var $form = $('#formId');
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: $form.serialize(),
success: function(response) {
$('#loading').fadeOut(function() {
// Get only text from the body of the result
$('body').html($(response).find('body'));
});
}
});
This is really hacky though and I felt dirty writing that. Seriously. You should really make sure that the response returned isn't go to:
Reload CSS styles, scripts, etc.
Any specific title, scripts, styles, etc relevant to that page and search will not appear or be changed.
More than likely you just want to return the result to the query i.e. the search results of the form submitted. In which case just wrap the results in a container and .find('#container') instead of .find('body')
Try this:
<script type="text/javascript">
if (document.getElementById("safeForm4d").submitted.value == "false") {
document.getElementById("safeForm4d").submitted.value = "true";
setTimeout('document.getElementById("safeForm4d").submit()', 100);
} else {
document.getElementById("toHide").style.display="none";
}
</script>
You have quotes in the setTimeout event:
setTimeout('document.getElementById("safeForm4d").submit()', 100);
Change your script as follows:
<script type="text/javascript">
if (document.getElementById("safeForm4d").submitted.value == "false") {
document.getElementById("safeForm4d").submitted.value = "true";
if(Wicket.Browser.isIE()) {
setTimeout(document.getElementById("safeForm4d").submit(), 100);
} else {
setTimeout(document.getElementById("safeForm4d").submit(), 100);
}
} else {
document.getElementById("toHide").style.display="none";
}
</script>
Finally solved my question, may be useful for others:
Answer:
HTML source code:
<SCRIPT type="text/javascript">
var $ = jQuery.noConflict();
document.getElementById('toHide').style.display ="";
$('#toHide').doTimeout(1000, function() {
$('#toHide').find('#safeForm34').submit();
document.getElementById('myAnimatedImage').src = "../../img/load.gif";
});
</SCRIPT>
html:
<div id="toHide" class="pb-text-align-center">
<img src="img/load.gif" id='myAnimatedImage' style="margin-left: auto; margin-right: auto;"/>
<form wicket:id="safeForm" class="clearfix" />
</div>

Call function with setInterval in jQuery?

I'm trying to create a interval call to a function in jQuery, but it doesn't work! My first question is, can I mix common JavaScript with jQuery?
Should I use setInterval("test()",1000); or something like this:
var refreshId = setInterval(function(){
code...
}, 5000);
Where do I put the function that I call and how do I activate the interval? Is it a difference in how to declare a function in JavaScript compared to jQuery?
To write the best code, you "should" use the latter approach, with a function reference:
var refreshId = setInterval(function() {}, 5000);
or
function test() {}
var refreshId = setInterval(test, 5000);
but your approach of
function test() {}
var refreshId = setInterval("test()", 5000);
is basically valid, too (as long as test() is global).
Note that there is no such thing really as "in jQuery". You're still writing the Javascript language; you're just using some pre-made functions that are the jQuery library.
First of all: Yes you can mix jQuery with common JS :)
Best way to build up an intervall call of a function is to use setTimeout methode:
For example, if you have a function called test() and want to repeat it all 5 seconds, you could build it up like this:
function test(){
console.log('test called');
setTimeout(test, 5000);
}
Finally you have to trigger the function once:
$(document).ready(function(){
test();
});
This document ready function is called automatically, after all html is loaded.
I have written a custom code for setInterval function which can also help
let interval;
function startInterval(){
interval = setInterval(appendDateToBody, 1000);
console.log(interval);
}
function appendDateToBody() {
document.body.appendChild(
document.createTextNode(new Date() + " "));
}
function stopInterval() {
clearInterval(interval);
console.log(interval);
}
<!DOCTYPE html>
<html>
<head>
<title>setInterval</title>
</head>
<body>
<input type="button" value="Stop" onclick="stopInterval();" />
<input type="button" value="Start" onclick="startInterval();" />
</body>
</html>
jQuery is just a set of helpers/libraries written in Javascript. You can still use all Javascript features, so you can call whatever functions, also from inside jQuery callbacks.
So both possibilities should be okay.
setInterval(function() {
updatechat();
}, 2000);
function updatechat() {
alert('hello world');
}

Categories