简体   繁体   中英

javascript function not getting executed

I want to execute a javascript function in an external js file when the page is loaded. This is the code in the jsp file where the function is called from, I placed it at the bottom of the jsp

<%-- Begins countdown --%>
<script src="/pub/scripts/counter.js" type="text/javascript"></script>
<script type="text/javascript">
window.onload=startCountdown;
</script>

this is the function in the js file

function startCountdown() {
var TIMEOUT = 900000; 
var COUNT_BACK = 3;   
setTimeout("displayWarning("+COUNT_BACK+")", TIMEOUT);
}

when the page loads in the browser I see that the script is loaded but the startCountdown function never gets executed. How can I make this work?

我会在您的html中使用<body onload="startCountdown()"> ,以确保在执行脚本之前必须完全加载页面。

Change window.onload=startCountdown; to window.onload=startCountdown(); and use defer

<%-- Begins countdown --%>
<script defer src="/pub/scripts/counter.js" type="text/javascript"></script>
<script defer type="text/javascript">
window.onload=startCountdown();
</script>
this is the function in the js file

var startCountdown = function() {
var TIMEOUT = 900000; 
var COUNT_BACK = 3;   
setTimeout("displayWarning("+COUNT_BACK+")", TIMEOUT);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM