最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Why can't I use javascript setInterval with a function in an external file? - Stack Overflow

programmeradmin5浏览0评论

The following works perfectly fine...displays an alert every 10 seconds

<script type='text/javascript'>
    function letsTest(){
        alert("it works");
    }
    var uptimeId = window.setInterval(letsTest, 10000);
</script>

But when I place my letsTest function in a file called javaScript.js, it no longer works.

main page:

<script src='lib/javaScript.js' type='text/javascript'>
    var uptimeId = window.setInterval(letsTest, 10000);
</script>

javaScript.js

function letsTest(){
    alert("it works");
}

I verified a thousand times over the path and spelling. I use my javaScript.js in other places as well. Is it possible to set an interval with a function from another file?

The following works perfectly fine...displays an alert every 10 seconds

<script type='text/javascript'>
    function letsTest(){
        alert("it works");
    }
    var uptimeId = window.setInterval(letsTest, 10000);
</script>

But when I place my letsTest function in a file called javaScript.js, it no longer works.

main page:

<script src='lib/javaScript.js' type='text/javascript'>
    var uptimeId = window.setInterval(letsTest, 10000);
</script>

javaScript.js

function letsTest(){
    alert("it works");
}

I verified a thousand times over the path and spelling. I use my javaScript.js in other places as well. Is it possible to set an interval with a function from another file?

Share Improve this question asked Oct 17, 2013 at 19:17 user2537383user2537383 3158 silver badges19 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 13
<script src='lib/javsScript.js' type='text/javascript'>
    var uptimeId = window.setInterval(letsTest, 10000);
</script>

You cannot provide both a src and a body for a <script> tag. One or the other.

You'll have to use two <script> tags:

<script src='lib/javaScript.js'></script>

<script>
   var uptimeId = setInterval(letsTest, 10000);
</script>

Actually the reason behind it may be ,that the variable uptimeId is not accessible inside the file javascript.js. Please let me know if I am wrong.

发布评论

评论列表(0)

  1. 暂无评论