2017-08-24 185 views
-5

我建立了一个网站,当您刷新网站时,它会闪现我的随机博客文章。但我希望能够每隔10-15秒向我展示另一个随机文章,而不必刷新网页。我正在考虑某种定时循环,每10秒钟运行一个循环内部的代码,选择一个随机的帖子(我不知道我的代码是否有什么要做,但如果有人想要它,我会编辑问题包括代码)。JavaScript每10秒计时循环

<% blogs.forEach(function(blog){ %> 
     <% blog.created.setHours(0,0,0,0) %> 


     <% }) %> 



<% specificBlogs = blogs.filter((blog)=>blog.created.toLocaleString() === 
today.toLocaleString()) %> 
<div class="ui main text container"> 
<div class="ui huge header">Post of the day</div> 
<div class="ui top attached segment"> 
    <div class="ui divided items"> 
    <%function myFunction() {%> 
    <% blogs.sort(function(a, b){return 0.5 - Math.random()});%> 

<%}%> 
    <%  function shuffle(a) { %> 
<% var j, x, i; %> 
    <% for (i = a.length; i; i--) { %> 
<%  j = Math.floor(Math.random() * i); %> 
<%  x = a[i - 1]; %> 
<%  a[i - 1] = a[j]; %> 
    <%  a[j] = x; %> 
<% } %> 
<%} %> 
     <% shuffle(specificBlogs); %> 
    <% specificBlogs.splice(1)%> 
     <% specificBlogs.forEach(function(blog){ %> 
      <div class="item"> 
       <div class="image"> 
        <img src="<%= blog.image %>" > 
       </div> 
       <div class="content"> 
        <a class="header" href="/blogs/<%= blog._id %>"> 
    <%=blog.title%></a> 
        <div class="meta"> 
         <span><%= blog.created.toDateString() %></span> 
        </div> 
        <div class="description"> 
         <p><%- blog.body.substring(0, 100) %>...</p> 
        </div> 
        <div class="extra"> 
         <a class="ui floated basic violet button" 
    href="/blogs/<%= blog._id %>"> 
          Read More 
          <i class="right chevron icon"></i> 
         </a> 
        </div> 
       </div> 
      </div> 
     <% }) %> 
     </div> 
     </div> 
    </div> 
+0

所以..加载数据,显示数据,选择随机,极尽每10秒......不同的台阶上加载这一点。你有尝试过吗? – GolezTrol

+0

蒂莫西你写的代码不起作用 –

+0

GolezTrol我的代码有效。我只是不知道如何做定时循环。 –

回答

1

这里是每10秒运行一次函数的脚本,您可以创建一个脚本来随机显示您的帖子。 时间是以毫秒为单位设置的,所以10.000毫秒是10秒。 只需将“YourFunction()”替换为要用于绘制帖子的函数即可。

setInterval(function(){YourFunction();}, 10000);

+0

当我把我的代码放在那里它不显示任何东西。这就像我删除了代码。 –

+0

@fensdfd如果你发布了你的代码,它会更有帮助。给我们一些工作,而不必猜测 –

+0

我添加了我的代码 –