Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Change the code of the clock project such that the clock automatically updates a

ID: 3877590 • Letter: C

Question

Change the code of the clock project such that the clock automatically updates at regular intervals, instead of when the button is clicked. [Hint: Use a timer such as setInterval() or setTimeout().] JavaScript

<!DOCTYPE html>

<html>

<head>

<title> Ajax Clock </title>

<style>

#clock {

font: 32px normal verdana, helvetica, sans-serif;

}

</style>

<script src="ajax.js"></script>

<script>

window.onload=function()

{

document.getElementById(" btn1").>

}

</script>

</head>

<body>

<input id ="btn1" type ="button" value ="Get Time"/>

<br/>

< div id ="clock"></ div>

</body>

</html>

ajax.js

function getXMLHttpRequest()

{

try {

try {

return new

ActiveXObject("Microsoft.XMLHTTP");

}

catch(e) {

return new ActiveXObject("Msxml2.XMLHTTP");

}

}

catch(e) {

return new XMLHttpRequest();

}

}

function callAjax()

{

var url = "clock.php";

var myRandom = parseInt(Math.random()*99999999);

myRequest. open("GET", url + "?rand=" + myRandom,true);

myRequest.onreadystatechange = responseAjax;

myRequest.send(null);

}

function responseAjax()

{

if( myRequest.readyState == 4)

{

if( myRequest.status == 200)

{ var now = new Date();

var localTime = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();

var serverTime = myRequest.responseText;

document.getElementById("clock").innerHTML = "Server: " + serverTime + "<br />Local: " + localTime;

} else {

alert(" An error has occurred: " + myRequest.statusText);

}

}

}

var myRequest = getXMLHttpRequest();

Explanation / Answer

Replace below code

window.onload=function()

{ document.getElementById(" btn1"). }

with

window.onload=function()

{

setInterval(function(){

callAjax(); },

3000); // setting interval of 3 seconds

}

As clock.php is not provided, so I am unable to test this scenario. but setinterval function is working fine as I have tested on my local data.

Let me know if you have any doubt.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote