Javascript 计数器只工作一次 [英] Javascript counter works only once

查看:34
本文介绍了Javascript 计数器只工作一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这里有一个 jsfiddle - http://jsfiddle.net/5z2vu47a/

I have a jsfiddle here - http://jsfiddle.net/5z2vu47a/

这是一个简单的计时器,可以更改从数组中获取的文本

It's a simple timer that should change text that taken from and array

定时器只工作一次.

为什么定时器不继续工作.

Why does the timer not continue to work.

var name_arr = ['learn', 'product', 'buying', 'selling', 'marketing', 'managing', ];
var counter = 0;

function names(){
    alert(counter);
    $('.text p').text(name_arr[counter]);
    counter++;
    alert(counter);
}

setTimeout(names, 1000);

推荐答案

您需要使用 setInterval

setInterval(names, 1000);

names 函数中,还要检查计数器值是否不应超过name_arr.length.

In the names function, also check that the counter value should not exceed the name_arr.length.

function names(){
    alert(counter);
    $('.text p').text(name_arr[counter]);
    if(counter<(name_arr.length-1))
     counter++;
    else
     counter=0;
    alert(counter);
}

这篇关于Javascript 计数器只工作一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆